【问题标题】:ValueError when using matplotlib tight_layout()使用 matplotlib 紧密布局()时出现 ValueError
【发布时间】:2014-06-09 22:32:58
【问题描述】:

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

我正在尝试使用 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

数据处理循环完成并创建所有子图后,我最终以

fig.tight_layout()
fig.savefig(str(location))

据我所知,这应该可以,但是当调用tight_layout() 时,我从函数self.subplotpars 中得到一个ValueError:left cannot be >= right。我的问题是:如何找出导致此错误的原因以及如何解决?

【问题讨论】:

  • 请向我们展示完整的 trackback 和一个会产生问题的可运行代码示例。
  • 我对你的问题有点困惑。您能否提供您的代码的运行示例?这样我就可以更清楚地了解您真正想要什么以及哪里可能出错

标签: python matplotlib


【解决方案1】:

我以前遇到过这个错误,我有一个适合我的解决方案。我不确定它是否对你有用。在 matplotlib 中,命令

plt.fig.subplots_adjust() 

可用于拉伸情节。左侧和底部拉伸越多,数字越小,而顶部和右侧拉伸越多,数字越大。所以如果左边大于或等于右边,或者底部大于或等于顶部,那么图表就会翻转。我将命令调整为如下所示:

fig = plt.figure()
fig.subplots_adjust(bottom = 0)
fig.subplots_adjust(top = 1)
fig.subplots_adjust(right = 1)
fig.subplots_adjust(left = 0)

然后你可以自己填写数字来调整这个,只要把左边和底部保持小即可。我希望这能解决您的问题。

【讨论】:

    猜你喜欢
    • 2021-01-11
    • 2014-05-09
    • 2012-03-25
    • 2021-01-28
    • 2021-07-24
    • 2018-12-14
    • 2016-05-25
    • 2018-06-02
    • 1970-01-01
    相关资源
    最近更新 更多