python - 使用 matplotlib tight_layout() 时出现 ValueError

标签 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

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

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

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

最佳答案

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

plt.fig.subplots_adjust() 

可用于对情节进行排序。数字越小,左侧和底部拉伸(stretch)得越多,数字越大,顶部和右侧拉伸(stretch)得越多。因此,如果左边大于或等于右边,或者底部大于或等于顶部,那么图形就会翻转过来。我将命令调整为如下所示:

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

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

关于python - 使用 matplotlib tight_layout() 时出现 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22708888/

相关文章:

python - 如何随时间按类别绘制

python - 如何从内循环跳转到外循环的开头

python - 循环变量感知 numpy 的切片和向量化计算

python - 使用 MySQL 从 Django QuerySet 获取不同的值

python - Seaborn 调色板 - 防止颜色回收

python - Matplotlib 绘图有斜线

python - Seaborn factor plot hue 要求不为空 "cells"

python - 如果列中的元素全部出现在列表中并且 pandas 中没有其他内容,则 Oly 子集分组

python - NumPy:如何快速归一化许多向量?

python - 在 PyQt 中使用 matplotlib 图