Matplotlib tight_layout引起运行时错误

11

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

我创建了6个子图作为示例,并希望使用tight_layout()整理它们重叠的文本,但是我收到了以下运行时错误。

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()

我最初怀疑问题可能是由于具有不同大小的子图,然而紧凑布局指南似乎表明这不应该是一个问题。任何帮助/建议将不胜感激。


给那些点踩的人:你们能解释一下为什么觉得这个问题应该被点踩吗?如果你觉得它可以在某些方面得到改进,请告诉我。 - Ffisegydd
1个回答

11

虽然在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()

第一个参数给出了网格的维度,第二个给出了子图左上角的网格位置,而rowspancolspan参数说明了每个子图应该延伸多少个网格点。


如果您使用IPython,则会从回溯中的每个步骤获得更多的上下文行,这是有帮助的。我已将此添加到我的答案中。 - mwaskom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接