简体   繁体   English

使用matplotlib时的ValueError tight_layout()

[英]ValueError when using matplotlib tight_layout()

Ok, this is my first time asking a question on here, so please be patient with me ;-) 好的,这是我第一次在这里问一个问题,所以请耐心等待我;-)

I'm trying to create a series of subplots (with two y-axes each) in a figure using matplotlib and then saving that figure. 我正在尝试使用matplotlib在图中创建一系列子图(每个图中有两个y轴),然后保存该图。 I'm using GridSpec to create a grid for the subplots and realised that they're overlapping a little, which I don't want. 我正在使用GridSpec为子图创建一个网格,并意识到它们重叠了一点,这是我不想要的。 So I'm trying to use tight_layout() to sort this out, which according to the matplotlib documentation should work just fine. 所以我正在尝试使用tight_layout()对其进行排序,根据matplotlib文档应该可以正常工作。 Simplifying things a bit, my code looks something like this: 稍微简化一下,我的代码看起来像这样:

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

After the loop for data processing is done and I have created all the subplots, I eventually end with 在完成数据处理循环并创建了所有子图之后,我最终结束了

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

As far as I can work out, this should work, however when calling tight_layout(), I get a ValueError from the function self.subplotpars: left cannot be >= right. 至于我可以解决,这应该工作,但是当调用tight_layout()时,我从函数self.subplotpars得到一个ValueError:left不能> = right。 My question is: How do I figure out what's causing this error and how do I fix it? 我的问题是:我如何找出导致此错误的原因以及如何解决?

I've had this error before, and I have a solution that worked for me. 我以前遇到过这个错误,我有一个适合我的解决方案。 I'm not sure if it will work for you though. 我不确定它是否适合你。 In matplotlib, the command 在matplotlib中,命令

plt.fig.subplots_adjust() 

can be used to sort of stretch the plot. 可以用来拉伸情节。 The left and bottom stretch more the smaller the number gets, while the top and right stretch more the greater the number is. 左侧和底部伸展越多,数字越小,而顶部和右侧伸展越多,数字越大。 So if left is greater than or equal to the right, or bottom is greater than or equal to the top, than the graph would kind of flip over. 因此,如果left大于或等于右边,或者bottom大于或等于顶部,则图形会翻转。 I adjusted my command to look like this: 我调整了我的命令看起来像这样:

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

Then you can fill in your own numbers to adjust this, as long as you keep the left and bottom smaller. 然后你可以填写你自己的数字来调整它,只要你保持左边和底部较小。 I hope this fixes your problem. 我希望这可以解决你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM