如何调整带有截断或重叠标签的填充方式

483

使用子图更新MRE

  • 我不确定原问题和MRE的有用性。对于大尺寸的x和y标签,边距填充似乎已经被正确地调整了。
  • 使用子图可以重现此问题。
  • 使用matplotlib 3.4.2
fig, axes = plt.subplots(ncols=2, nrows=2, figsize=(8, 6))
axes = axes.flatten()

for ax in axes:
    ax.set_ylabel(r'$\ln\left(\frac{x_a-x_b}{x_a-x_c}\right)$')
    ax.set_xlabel(r'$\ln\left(\frac{x_a-x_d}{x_a-x_e}\right)$')

plt.show()

enter image description here

原始内容

我在使用matplotlib绘制数据集,其中我的横坐标标签非常“高”(它是在TeX中呈现的公式,包含一个分数,因此高度相当于几行文本)。

无论如何,在绘制图形时,公式的底部总是被裁剪掉。改变图像大小似乎对此没有帮助,而且我还没能找到如何向上移动x轴以为横坐标标签腾出空间的方法。这样的解决方案可能是一个合理的临时解决方案,但很好的方法是让matplotlib自动识别标签是否被裁切并相应地调整大小。

这是我所说的例子:

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)$', fontsize=50)
plt.title('Example with matplotlib 3.4.2\nMRE no longer an issue')
plt.show()

这里输入图片描述

整个纵轴标签都可见,但横轴标签被截断了。

如果这是机器特定的问题,那么我正在使用OSX 10.6.8和matplotlib 1.0.0。


36
你可能还想尝试使用 plt.savefig("test.png",bbox_inches='tight'):https://dev59.com/R2Ei5IYBdhLWcg3wbr3S - Yibo Yang
8个回答

673

使用:

import matplotlib.pyplot as plt

plt.gcf().subplots_adjust(bottom=0.15)

# alternate option without .gcf
plt.subplots_adjust(bottom=0.15)

为了为标签腾出空间,在这里使用plt.gcf()来获取当前图形。plt.gca()也可以被用来获取当前的Axes

编辑:

自从我回答这个问题后,matplotlib添加了plt.tight_layout()函数。

查看matplotlib教程:紧凑布局指南

因此我建议使用它:

fig, axes = plt.subplots(ncols=2, nrows=2, figsize=(8, 6))
axes = axes.flatten()

for ax in axes:
    ax.set_ylabel(r'$\ln\left(\frac{x_a-x_b}{x_a-x_c}\right)$')
    ax.set_xlabel(r'$\ln\left(\frac{x_a-x_d}{x_a-x_e}\right)$')

plt.tight_layout()
plt.show()

在此输入图片描述


可以将其合并为一行代码:fig, axes = plt.subplots(ncols=2, nrows=2, figsize=(8, 6), tight_layout=True),而不是之后再添加 plt.tight_layout() - Trenton McKinney

327

如果您想将其存储到文件中,则可以使用bbox_inches = " tight"参数来解决:

plt.savefig('myfile.png', bbox_inches="tight")

203

一种简单的选择是配置matplotlib以自动调整绘图大小。对我来说效果很好,但我不确定为什么默认情况下没有激活它。

方法1

在您的matplotlibrc文件中设置此项。

figure.autolayout : True

请参阅以下链接以获取有关自定义matplotlibrc文件的更多信息:http://matplotlib.org/users/customizing.html

方法2

可以像这样在运行时更新rcParams

from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
使用这种方法的优点在于,您的代码可以在不同配置的计算机上生成相同的图形。

10

plt.autoscale() 对我很有效。


7
你可以通过以下方式在$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
...

7

0

出于某种原因,ShareX 被设置为 True,所以我将其改回 False,然后它就正常工作了。

df.plot(........,sharex=False)

-3

你需要使用剪刀来修改轴范围:

import sizzors as sizzors_module

sizzors_module.reshape_the_axis(plt).save("literlymylief.tiff")

2
到底什么是sizzors? - jtlz2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接