Python 第二个 y 轴标签被切断
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21288062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Second y-axis label getting cut off
提问by zje
I'm trying to plot two sets of data in a bar graph with matplotlib, so I'm using two axes with the twinx()method. However, the second y-axis label gets cut off. I've tried a few different methods with no success (tight_layout(), setting the major_pads in rcParams, etc...). I feel like the solution is simple, but I haven't come across it yet.
我正在尝试使用 matplotlib 在条形图中绘制两组数据,因此我在该twinx()方法中使用了两个轴。但是,第二个 y 轴标签被切断。我尝试了几种不同的方法,但都没有成功(tight_layout()在major_pads 中设置srcParams等...)。我觉得解决方案很简单,但我还没有遇到过。
Here's a MWE:
这是一个 MWE:
#!/usr/bin/env python
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.rcParams.update({'font.size': 21})
ax = plt.gca()
plt.ylabel('Data1') #Left side
ax2 = ax.twinx()
for i in range(10):
if(i%2==0):
ax.bar(i,np.random.randint(10))
else:
ax2.bar(i,np.random.randint(1000),color='k')
plt.ylabel('Data2') #Right
side plt.savefig("test.png")
侧面 plt.savefig("test.png")


采纳答案by zje
I just figured it out: the trick is to use bbox_inches='tight'in savefig.
我刚刚想通了:诀窍是bbox_inches='tight'在savefig.
E.G. plt.savefig("test.png",bbox_inches='tight')
例如 plt.savefig("test.png",bbox_inches='tight')


回答by Elliot
I encountered the same issue which plt.tight_layout()did not automatically solve.
Instead, I used the labelpad argument in ylabel/set_ylabelas such:
我遇到了plt.tight_layout()没有自动解决的相同问题。
相反,我在ylabel/ 中使用了 labelpad 参数set_ylabel:
ax.set_ylabel('label here', rotation=270, color='k', labelpad=15)
ax.set_ylabel('label here', rotation=270, color='k', labelpad=15)
I guess this was not implemented when you asked this question, but as it's the top result on google, hopefully it can help users of the current matplotlib version.
我猜当你问这个问题时这并没有实现,但由于它是谷歌上的最高结果,希望它可以帮助当前 matplotlib 版本的用户。

