为什么我的matlab插图在我的matplotlib图中切断了?

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腾出空间.

  • 我觉得很奇怪,人们需要额外拨打电话,为剧情的重要部分腾出空间.这背后的原因是什么? (115认同)
  • 什么是`gcf`和`gca`?你忽略了解释! (47认同)
  • @ColonelPanic``gcf()``和``gca()``分别是"获取当前数字"和"获取当前轴". (13认同)
  • 我遇到了同样的问题,虽然`tight_layout()`确实修复了xlabels截止,但遗憾的是它导致我的ylabel被切断(之前没有切断).然而,第一个补救措施(`subplots_adjust(bottom = 0.25)`)工作得很好.谢谢. (11认同)
  • 出于好奇,为什么你有`gcf().subplots_adjust`而不是`plt.subplots_adjust`?有区别吗? (3认同)
  • 以下是文档中示例的链接:http://matplotlib.org/examples/pylab_examples/subplots_adjust.html (2认同)
  • 我不得不使用plt.tight_layout()来修复它. (2认同)
  • @Max.那是因为`tight_layout`是`Figure`的方法,而不是`Axes`.Dunno在哪里`gca()`来自. (2认同)

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)


小智 9

plt.autoscale() 为我工作。


Jor*_*nds 7

还有一种方法可以使用 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


Мат*_*нер 5

您还可以将自定义填充设置为默认值,$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)