如何使用截断或重叠标签调整填充

2024-09-27 19:24:20 发布

您现在位置:Python中文网/ 问答频道 /正文

使用子批次更新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绘制一个数据集,其中我有一个相当“高”的xlabel(这是一个以TeX表示的公式,包含一个分数,因此其高度相当于几行文本)

在任何情况下,当我画数字时,公式的底部总是被切断。改变图形大小似乎对此没有帮助,而且我还不知道如何将x轴“向上”移动以为xlabel腾出空间。这样做是一个合理的临时解决方案,但最好能有一种方法让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()

enter image description here

整个ylabel可见,但是xlabel在底部被切断

如果这是一个特定于机器的问题,我将在OSX 10.6.8和matplotlib 1.0.0上运行它


Tags: rightmatplotlibshowplt标签axleft公式
3条回答

如果要将其存储到文件中,请使用bbox_inches="tight"参数进行求解:

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

一个简单的选项是配置matplotlib以自动调整打印大小。它非常适合我,我不知道为什么默认情况下不激活它

方法1

在matplotlibrc文件中设置此选项

figure.autolayout : True

有关自定义matplotlibrc文件的详细信息,请参见此处:http://matplotlib.org/users/customizing.html

方法2

像这样在运行时更新rcParams

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

使用这种方法的优点是,您的代码将在不同配置的机器上生成相同的图形

使用:

import matplotlib.pyplot as plt

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

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

要为标签腾出空间,其中^{}表示获取当前图形^也可以使用{a2},它获取当前的Axes

编辑:

自从我给出答案后,matplotlib添加了^{}函数

See matplotlib Tutorials: Tight Layout Guide

因此,我建议使用它:

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()

enter image description here

相关问题 更多 >

    热门问题