笔记
单击此处 下载完整的示例代码
自动缩放#
可以手动设置轴上的限制(例如),或者 Matplotlib 可以根据轴上已有的数据自动设置它们。这种自动缩放行为有许多选项,如下所述。ax.set_xlim(xmin, xmax)
我们将从一个简单的线图开始,显示自动缩放将轴限制扩展了 5%,超出了数据限制(-2π,2π)。

[<matplotlib.lines.Line2D object at 0x7f2cde5343a0>]
边距#
数据限制的默认边距为 5%:
(0.05, 0.05)
可以使用更大的边距margins
:
fig, ax = plt.subplots()
ax.plot(x, y)
ax.margins(0.2, 0.2)

通常,边距可以在 (-0.5, ∞) 范围内,其中负边距将轴限制设置为数据范围的子范围,即它们剪切数据。使用单个边距数字会影响两个轴,可以使用关键字参数x
或自定义单个边距y
,但不能组合位置和关键字接口。
fig, ax = plt.subplots()
ax.plot(x, y)
ax.margins(y=-0.2)

粘边#
有一些情节元素(Artist
s)通常没有边距使用。例如Axes.imshow
,在边距计算中不考虑伪彩色图像(例如,使用 创建)。

Text(0.5, 1.0, 'margins(0.2)')
这种对边距的覆盖由“粘性边缘”决定,这是一个Artist
可以禁止将边距添加到轴限制的类属性。可以通过更改 来禁用 Axes 上的粘边效果
use_sticky_edges
。艺术家有一个属性Artist.sticky_edges
,可以通过写入Artist.sticky_edges.x
或
更改粘边的值Artist.sticky_edges.y
。
以下示例显示了覆盖的工作原理以及何时需要。
fig, ax = plt.subplots(ncols=3, figsize=(16, 10))
ax[0].imshow(zz)
ax[0].margins(0.2)
ax[0].set_title("default use_sticky_edges\nmargins(0.2)")
ax[1].imshow(zz)
ax[1].margins(0.2)
ax[1].use_sticky_edges = False
ax[1].set_title("use_sticky_edges=False\nmargins(0.2)")
ax[2].imshow(zz)
ax[2].margins(-0.2)
ax[2].set_title("default use_sticky_edges\nmargins(-0.2)")

Text(0.5, 1.0, 'default use_sticky_edges\nmargins(-0.2)')
我们可以看到设置use_sticky_edges
为False会以请求的边距呈现图像。
虽然粘性边缘不会通过额外的边距增加轴限制,但仍会考虑负边距。这可以从第三幅图像的缩小限制中看出。
控制自动缩放#
默认情况下,每次向图中添加新曲线时都会重新计算限制:

Text(0.5, 1.0, 'Two curves')
但是,在某些情况下,您不想自动将视口调整为新数据。
禁用自动缩放的一种方法是手动设置轴限制。假设我们只想更详细地查看部分数据。xlim
即使我们向数据添加更多曲线,设置仍然存在。要重新计算新的限制调用Axes.autoscale
将手动切换功能。
fig, ax = plt.subplots(ncols=2, figsize=(12, 8))
ax[0].plot(x, y)
ax[0].set_xlim(left=-1, right=1)
ax[0].plot(x + np.pi * 0.5, y)
ax[0].set_title("set_xlim(left=-1, right=1)\n")
ax[1].plot(x, y)
ax[1].set_xlim(left=-1, right=1)
ax[1].plot(x + np.pi * 0.5, y)
ax[1].autoscale()
ax[1].set_title("set_xlim(left=-1, right=1)\nautoscale()")

Text(0.5, 1.0, 'set_xlim(left=-1, right=1)\nautoscale()')
我们可以使用以下命令检查第一个图是否已禁用自动缩放,第二个图是否已再次启用Axes.get_autoscale_on()
:
print(ax[0].get_autoscale_on()) # False means disabled
print(ax[1].get_autoscale_on()) # True means enabled -> recalculated
False
True
autoscale 函数的参数使我们能够精确控制自动缩放的过程。参数的组合enable
,并axis
为所选轴(或两者)设置自动缩放功能。该参数tight
将所选轴的边距设置为零。要保留其中一个的设置,
enable
或者tight
您可以将相反的设置设置为None,这样就不应该对其进行修改。但是,无论参数如何,设置enable
为None并严格设置为Trueaxis
都会影响两个轴。
fig, ax = plt.subplots()
ax.plot(x, y)
ax.margins(0.2, 0.2)
ax.autoscale(enable=None, axis="x", tight=True)
print(ax.margins())

(0, 0)
使用集合#
自动缩放适用于添加到轴的所有线条、补丁和图像。它不能与之合作的艺术家之一是Collection
. 将集合添加到轴后,必须手动触发
autoscale_view()
重新计算轴限制。
fig, ax = plt.subplots()
collection = mpl.collections.StarPolygonCollection(
5, rotation=0, sizes=(250,), # five point star, zero angle, size 250px
offsets=np.column_stack([x, y]), # Set the positions
offset_transform=ax.transData, # Propagate transformations of the Axes
)
ax.add_collection(collection)
ax.autoscale_view()

脚本总运行时间:(0分6.508秒)