【问题标题】:Matplotlib tight_layout causing RuntimeErrorMatplotlib 紧密布局导致 RuntimeError
【发布时间】:2014-05-09 04:02:35
【问题描述】:

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

【问题讨论】:

  • 致反对者:你能解释一下为什么你觉得这个问题应该被反对吗?如果您觉得它可以通过某种方式改进,请告诉我。

标签: python python-3.x matplotlib


【解决方案1】:

这绝对不是一个有用的错误消息,尽管 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,您将在回溯的每一步中获得更多的上下文行,这很有帮助。我已将此添加到我上面的答案中。
猜你喜欢
  • 2022-01-18
  • 2021-01-28
  • 2012-03-25
  • 2021-07-24
  • 1970-01-01
  • 2018-12-14
  • 2016-05-25
  • 2018-06-02
  • 2021-01-11
相关资源
最近更新 更多