gpt4 book ai didi

python - Matplotlib tight_layout 导致 RuntimeError

转载 作者:太空狗 更新时间:2023-10-29 20:21:33 26 4
gpt4 key购买 nike

我在使用 plt.tight_layout() 尝试整理具有多个子图的 matplotlib 图时遇到了问题。

我已经创建了 6 个子图作为示例,并想用 tight_layout() 整理它们重叠的文本,但是我得到以下 RuntimeError。

Traceback (most recent call last):
File ".\test.py", line 37, in <module>
fig.tight_layout()
File "C:\Python34\lib\site-packages\matplotlib\figure.py", line 1606, in tight_layout
rect=rect)
File "C:\Python34\lib\site-packages\matplotlib\tight_layout.py", line 334, in get_tight_layout_figure
raise RuntimeError("")
RuntimeError

这里给出了我的代码(我使用的是 Python 3.4)。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 3*np.pi, 1000)

fig = plt.figure()


ax1 = fig.add_subplot(3, 1, 1)

ax2 = fig.add_subplot(3, 2, 3)
ax3 = fig.add_subplot(3, 2, 4)

ax4 = fig.add_subplot(3, 3, 7)
ax5 = fig.add_subplot(3, 3, 8)
ax6 = fig.add_subplot(3, 3, 9)

for ax in [ax1, ax2, ax3, ax4, ax5, ax6]:
ax.plot(x, np.sin(x))

fig.tight_layout()

plt.show()

我最初怀疑问题可能来自不同大小的子图,但是 tight layout guide似乎暗示这应该不是问题。任何帮助/建议将不胜感激。

最佳答案

这绝对不是一条有用的错误消息,尽管 if 子句中有导致异常的提示。如果您使用 IPython,您将在回溯中获得一些额外的上下文。这是我在尝试运行您的代码时看到的内容:

    332         div_col, mod_col = divmod(max_ncols, cols)
333 if (mod_row != 0) or (mod_col != 0):
--> 334 raise RuntimeError("")

尽管您可以将 tight_layout 用于不同大小的子图,但它们必须按规则网格排列。如果您仔细查看文档,它实际上是在使用 plt.subplot2grid 函数来设置与您尝试执行的操作最相关的绘图。

因此,要准确获得您想要的内容,您必须将其布置在 3x6 网格上:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
fig = plt.figure()

# Top row
ax1 = plt.subplot2grid((3, 6), (0, 0), colspan=6)

# Middle row
ax2 = plt.subplot2grid((3, 6), (1, 0), colspan=3)
ax3 = plt.subplot2grid((3, 6), (1, 3), colspan=3)

# Bottom row
ax4 = plt.subplot2grid((3, 6), (2, 0), colspan=2)
ax5 = plt.subplot2grid((3, 6), (2, 2), colspan=2)
ax6 = plt.subplot2grid((3, 6), (2, 4), colspan=2)

# Plot a sin wave
for ax in [ax1, ax2, ax3, ax4, ax5, ax6]:
ax.plot(x, np.sin(x))

# Make the grid nice
fig.tight_layout()

enter image description here

第一个参数给出网格尺寸,第二个参数给出子图左上角的网格位置,rowspancolspan 参数表示网格中有多少个点每个子图都应该延伸过来。

关于python - Matplotlib tight_layout 导致 RuntimeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22734068/

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