matplotlib 轴('tight')不起作用?

Evg*_*eev 5 python layout plot axes matplotlib

根据文档ax.autoscale(tight=True)应该

如果为 True,则将查看限制设置为数据限制;

随着ax.axis('tight')是相似的:

'tight' 限制设置为显示所有数据

(原文如此)

我们甚至在这个问题的截图中看到它是有效的。

但是无论我尝试什么,它似乎都不适用于以下简单示例。这是我输入的内容jupyter-qtconsole

In [27]: f, ax = plt.subplots(1)

In [28]: ax.plot([0, 1], [1, 0])
Out[28]: [<matplotlib.lines.Line2D at 0x825abf0>]

In [29]: ax.axis('tight')
Out[29]: (-0.050000000000000003, 1.05, -0.050000000000000003, 1.05)

In [30]: ax.autoscale(tight=True)

In [31]: plt.axis('tight')
Out[31]: (-0.050000000000000003, 1.05, -0.050000000000000003, 1.05)

In [32]: plt.autoscale(tight=True)

In [33]: ax.plot([0, 1], [1, 0])
Out[33]: [<matplotlib.lines.Line2D at 0x825a4d0>]

In [34]: ax.autoscale(enable=True, axis='x', tight=True)
Run Code Online (Sandbox Code Playgroud)

在这些命令中,绘图的限制不会改变:

边距可见

我可能做错了什么?

Imp*_*est 6

通过设置 ,autoscale您应该会看到tight=True和之间所需的差异tight=False

f, (ax, ax2) = plt.subplots(ncols=2)

ax.plot([0, 1], [1, 0], label="tight=True")
ax.autoscale(enable=True, axis='both', tight=True)

ax2.plot([0, 1], [1, 0], label="tight=False")
ax2.autoscale(enable=True, axis='both', tight=False)

ax.legend()
ax2.legend()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

你可能会注意到这ax.axis("tight")不相关;它只在文档中说明

'tight' 限制设置为显示所有数据

确实如此,显示了所有数据(它没有说明将视图限制设置为完全数据)。


小智 3

你不一定做错了什么。您使用的是 matplotlib 版本 2(或更高版本)。在此版本中,默认绘图布局已更改,以便轴的两端添加了 5% 的填充。这是描述绘图布局的链接:https://matplotlib.org/users/dflt_style_changes.html#plot-layout

从链接中,要将其改回“经典”样式,请使用:

mpl.rcParams['axes.autolimit_mode'] = 'round_numbers'
mpl.rcParams['axes.xmargin'] = 0
mpl.rcParams['axes.ymargin'] = 0
Run Code Online (Sandbox Code Playgroud)