为什么我的xlabel在我的matplotlib图中被切断?

我正在使用matplotlib绘制一个数据集,其中我有一个相当“高”的xlabel(这是一个在TeX中呈现的包含分数的公式,因此具有相当于几行文本的高度)的xlabel。

无论如何,当我绘制数字时,公式的底部总是被切断。 改变graphics大小似乎没有帮助,我还没有能够弄清楚如何将x轴“向上”移动以为xlabel腾出空间。 像这样的东西将是一个合理的临时解决scheme,但是有什么好的方法可以使matplotlib自动识别标签被切断并相应resize。

这里是我的意思的一个例子:

 import matplotlib.pyplot as plt plt.figure() plt.ylabel(r'$\ln\left(\frac{x_a-x_b}{x_a-x_c}\right)$') plt.xlabel(r'$\ln\left(\frac{x_a-x_d}{x_a-x_e}\right)$') plt.show() 

而你可以看到整个ylabel,xlabel在底部被切断。

在这种情况下,这是一个特定于计算机的问题,我使用matplotlib 1.0.0在OSX 10.6.8上运行

使用:

 import matplotlib.pyplot as plt plt.gcf().subplots_adjust(bottom=0.15) 

为标签腾出空间。

编辑:

因为我给出了答案, matplotlib已经添加了tight_layout()函数。 所以我build议使用它:

 plt.tight_layout() 

应该为xlabel腾出空间。

一个简单的select是configurationmatplotlib自动调整绘图大小。 这对我来说是完美的,我不确定为什么它没有被默认激活。

方法1

将其设置在matplotlibrc文件中

 figure.autolayout : True 

有关定制matplotlibrc文件的更多信息,请参阅这里: http : //matplotlib.org/users/customizing.html

方法2

像这样在运行时更新rcParams

 from matplotlib import rcParams rcParams.update({'figure.autolayout': True}) 

使用这种方法的优点是,您的代码将在不同configuration的机器上生成相同的graphics。

您还可以在$HOME/.matplotlib/matplotlib_rc中将自定义填充设置为默认值,如下所示。 在下面的示例中,我修改了底部和左侧的开箱即用的填充:

 # The figure subplot parameters. All dimensions are a fraction of the # figure width or height figure.subplot.left : 0.1 #left side of the subplots of the figure #figure.subplot.right : 0.9 figure.subplot.bottom : 0.15 ...