使用matplotlib时的ValueError tight_layout()

all*_*lly 12 python matplotlib

好的,这是我第一次在这里问一个问题,所以请耐心等待我;-)

我正在尝试使用matplotlib在图中创建一系列子图(每个图中有两个y轴),然后保存该图.我正在使用GridSpec为子图创建网格,并意识到它们重叠了一点,这是我不想要的.所以我正在尝试使用tight_layout()对其进行排序,根据matplotlib文档应该可以正常工作.稍微简化一下,我的代码看起来像这样:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(num=None, facecolor='w', edgecolor='k')
grid = gridspec.GridSpec(2, numRows) 
# numRows comes from the number of subplots required

# then I loop over all the data files I'm importing and create a subplot with two y-axes each time
  ax1 = fig.add_subplot(grid[column, row])
  # now I do all sorts of stuff with ax1...
  ax2 = ax1.twinx()
  # again doing some stuff here
Run Code Online (Sandbox Code Playgroud)

在完成数据处理循环并创建了所有子图之后,我最终结束了

fig.tight_layout()
fig.savefig(str(location))
Run Code Online (Sandbox Code Playgroud)

至于我可以解决,这应该工作,但是当调用tight_layout()时,我从函数self.subplotpars得到一个ValueError:left不能> = right.我的问题是:我如何找出导致此错误的原因以及如何解决?

小智 6

我之前曾遇到过此错误,并且有一个适合我的解决方案。我不确定它是否对您有用。在matplotlib中,命令

plt.fig.subplots_adjust() 
Run Code Online (Sandbox Code Playgroud)

可以用来拉伸剧情。左侧和底部的伸展程度越大,数字越小,而顶部和右侧的伸展程度越大,数字越大。因此,如果left大于或等于right或bottom大于或等于top,则该图将发生翻转。我将命令调整为如下所示:

fig = plt.figure()
fig.subplots_adjust(bottom = 0)
fig.subplots_adjust(top = 1)
fig.subplots_adjust(right = 1)
fig.subplots_adjust(left = 0)
Run Code Online (Sandbox Code Playgroud)

然后,您可以填写自己的数字进行调整,只要保持左侧和底部较小即可。我希望这可以解决您的问题。