[英]Matplotlib tight_layout causing RuntimeError
我在使用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()
我最初懷疑問題可能來自於具有不同大小的子圖,但是嚴格的布局指南似乎表明這應該不是問題。 任何幫助/建議將不勝感激。
這絕對不是一個有用的錯誤消息,盡管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()
第一個參數給出了網格尺寸,第二個參數給出了子圖的左上角網格位置,而rowspan
和colspan
參數表示網格中每個子圖應該延伸多少個點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.