如何调整带有截止或重叠标签的填充
- 2025-01-03 08:40:00
- admin 原创
- 122
问题描述:
更新了 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'$lnleft(rac{x_a-x_b}{x_a-x_c}
ight)$')
ax.set_xlabel(r'$lnleft(rac{x_a-x_d}{x_a-x_e}
ight)$')
plt.show()
原来的
我正在绘制一个数据集matplotlib
,其中有一个相当“高”的 xlabel(它是一个用 TeX 呈现的公式,包含一个分数,因此其高度相当于几行文本)。
无论如何,当我绘制图形时,公式的底部总是被截断。更改图形大小似乎对此没有帮助,而且我还没能弄清楚如何将 x 轴“向上”移动以便为 xlabel 腾出空间。类似这样的方法可能是一个合理的临时解决方案,但如果有一种方法可以让 matplotlib 自动识别标签被截断并相应地调整大小,那就太好了。
下面是我所指的一个例子:
import matplotlib.pyplot as plt
plt.figure()
plt.ylabel(r'$lnleft(rac{x_a-x_b}{x_a-x_c}
ight)$')
plt.xlabel(r'$lnleft(rac{x_a-x_d}{x_a-x_e}
ight)$', fontsize=50)
plt.title('Example with matplotlib 3.4.2
MRE no longer an issue')
plt.show()
整个 ylabel 可见,但是 xlabel 在底部被截断。
如果这是特定于机器的问题,我在 OSX 10.6.8 上使用 matplotlib 1.0.0 运行它
解决方案 1:
使用:
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'$lnleft(rac{x_a-x_b}{x_a-x_c}
ight)$')
ax.set_xlabel(r'$lnleft(rac{x_a-x_d}{x_a-x_e}
ight)$')
plt.tight_layout()
plt.show()
解决方案 2:
如果你想将其存储到文件中,你可以使用bbox_inches="tight"
参数来解决:
plt.savefig('myfile.png', bbox_inches="tight")
解决方案 3:
一个简单的选项是配置 matplotlib 以自动调整绘图大小。对我来说,它运行完美,我不确定为什么它没有默认激活。
方法 1
在你的 matplotlibrc 文件中设置此项
figure.autolayout : True
有关自定义 matplotlibrc 文件的更多信息,请参见:http: //matplotlib.org/users/customizing.html
方法 2
在运行时像这样更新 rcParams
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
使用此方法的优点是您的代码将在不同配置的机器上生成相同的图形。
解决方案 4:
plt.autoscale()
对我有用。
解决方案 5:
还有一种方法可以使用 OOP 接口来实现这一点,tight_layout
直接应用于图形:
fig, ax = plt.subplots()
fig.set_tight_layout(True)
https://matplotlib.org/stable/api/figure_api.html
解决方案 6:
您还可以将自定义填充设置为默认值,$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:
更现代的建议是使用layout='constrained'
。在这种情况下,它不会有太大的不同,但比更灵活layout='tight'
。
fig, axes = plt.subplots(ncols=2, nrows=2, figsize=(8, 6),
layout='constrained')
axes = axes.flatten()
for ax in axes:
ax.set_ylabel(r'$lnleft(rac{x_a-x_b}{x_a-x_c}
ight)$')
ax.set_xlabel(r'$lnleft(rac{x_a-x_d}{x_a-x_e}
ight)$')
plt.show()
解决方案 8:
由于某种原因,sharex 被设置为 True,所以我将其改回 False,并且工作正常。
df.plot(........,sharex=False)
解决方案 9:
您需要使用 sizzors 来修改轴范围:
import sizzors as sizzors_module
sizzors_module.reshape_the_axis(plt).save("literlymylief.tiff")
扫码咨询,免费领取项目管理大礼包!