gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:48:04 25 4
gpt4 key购买 nike

我正在尝试制作一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com