And*_*rew 265 python matplotlib
我正在绘制一个数据集,使用的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)$')
plt.show()
Run Code Online (Sandbox Code Playgroud)
当你可以看到整个ylabel时,xlabel在底部被切断.
在这是特定于机器的问题的情况下,我在OSX 10.6.8上使用matplotlib 1.0.0运行它
til*_*ten 391
使用:
import matplotlib.pyplot as plt
plt.gcf().subplots_adjust(bottom=0.15)
Run Code Online (Sandbox Code Playgroud)
为标签腾出空间.
编辑:
既然我给出了答案,matplotlib就添加了这个tight_layout()功能.所以我建议使用它:
plt.tight_layout()
Run Code Online (Sandbox Code Playgroud)
应该为xlabel腾出空间.
Ami*_*ich 133
一个简单的选择是配置matplotlib以自动调整绘图大小.它对我来说非常合适,我不确定为什么默认情况下它没有被激活.
方法1
在matplotlibrc文件中设置它
figure.autolayout : True
Run Code Online (Sandbox Code Playgroud)
有关自定义matplotlibrc文件的更多信息,请参见此处:http://matplotlib.org/users/customizing.html
方法2
像运行时一样在运行时更新rcParams
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
Run Code Online (Sandbox Code Playgroud)
使用此方法的优点是您的代码将在不同配置的计算机上生成相同的图形.
Gui*_*ido 55
如果要将其存储到文件中,可以使用bbox_inches="tight"参数解决它:
plt.savefig('myfile.png', bbox_inches = "tight")
Run Code Online (Sandbox Code Playgroud)
还有一种方法可以使用 OOP 接口来执行此操作,tight_layout直接应用于图形:
fig, ax = plt.subplots()
fig.set_tight_layout(True)
Run Code Online (Sandbox Code Playgroud)
https://matplotlib.org/stable/api/figure_api.html
您还可以将自定义填充设置为默认值,$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
...
Run Code Online (Sandbox Code Playgroud)