Matplotlib tight_layout导致RuntimeError

时间:2014-03-29 17:06:15

标签: python python-3.x matplotlib

使用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似乎表明这应该不是问题。任何帮助/建议将不胜感激。

1 个答案:

答案 0 :(得分:9)

这绝对不是一个有用的错误消息,尽管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参数表示网格中每个子图应该延伸多少个点。

相关问题