python - 如何在一个图中制作超过 10 个子图?

标签 python matplotlib figure subplot

我正在尝试制作一个 5x4 的子图网格,通过查看示例,在我看来最好的方法是:

import matplotlib.pyplot as plt
plt.figure()
plt.subplot(221)

其中子图 (22) 中的前两个数字表示它是一个 2x2 网格,第三个数字表示您正在制作 4 个网格中的哪一个。然而,当我尝试这个时,我不得不去:

plt.subplot(5420)

我得到了错误:

ValueError: Integer subplot specification must be a three digit number.  Not 4

那么这是否意味着您不能制作超过 10 个子图,或者有解决方法,还是我误解了它的工作原理?

提前谢谢你。

最佳答案

您可能正在寻找 GridSpec .您可以说明网格的大小 (5,4) 和每个图的位置(行 = 0,列 = 2,即 - 0,2)。检查以下示例:

import matplotlib.pyplot as plt

plt.figure(0)
ax1 = plt.subplot2grid((5,4), (0,0))
ax2 = plt.subplot2grid((5,4), (1,1))
ax3 = plt.subplot2grid((5,4), (2, 2))
ax4 = plt.subplot2grid((5,4), (3, 3))
ax5 = plt.subplot2grid((5,4), (4, 0))
plt.show()

,结果是:

gridspec matplotlib example

您是否应该构建嵌套循环来制作完整的网格:

import matplotlib.pyplot as plt

plt.figure(0)
for i in range(5):
    for j in range(4):
        plt.subplot2grid((5,4), (i,j))
plt.show()

,你会得到这个:

full 5x4 grid in gridspec matplotlib

绘图与任何子绘图的工作方式相同(直接从您创建的轴调用它):

import matplotlib.pyplot as plt
import numpy as np

plt.figure(0)
plots = []
for i in range(5):
    for j in range(4):
        ax = plt.subplot2grid((5,4), (i,j))
        ax.scatter(range(20),range(20)+np.random.randint(-5,5,20))
plt.show()

,结果是:

multiple scatterplots in gridspec

请注意,您可以为图表提供不同的尺寸(说明每个图表的列数和行数):

import matplotlib.pyplot as plt

plt.figure(0)
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2)
ax3 = plt.subplot2grid((3,3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3,3), (2, 0))
ax5 = plt.subplot2grid((3,3), (2, 1))
plt.show()

,因此:

different sizes for each plot in gridspec

在我一开始提供的链接中,您还可以找到删除标签等内容的示例。

关于python - 如何在一个图中制作超过 10 个子图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37424530/

相关文章:

python - 子图中的 Matplotlib 图例

MATLAB:为图中的数据光标永久设置 "Text Update Function"

php - Wordpress 3.9.x - 从图形元素中删除内联宽度

python - 如何告诉 Matplotlib 创建第二个(新)图,然后在旧图上绘制?

python - 删除子图

python - 使用 sklearn KNN 显示最近邻居

python - 一组动态成员的自然命名方案

python - 完全循环具有不同起始索引的列表

python - knitr:python 引擎输出不在 .md 或 .html 中

python - 在 C++ 应用程序中执行已解析的脚本/片段