自动设置刻度位置#

设置刻度自动放置的行为。

默认情况下,Matplotlib 会选择刻度的数量和位置,以确保轴上有合理的刻度数量,并且它们位于“圆整”的数值上。

因此,绘图的边缘可能没有刻度。

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(19680801)

fig, ax = plt.subplots()
dots = np.linspace(0.3, 1.2, 10)
X, Y = np.meshgrid(dots, dots)
x, y = X.ravel(), Y.ravel()
ax.scatter(x, y, c=x+y)
plt.show()
auto ticks

如果你想在整数值处保留刻度,并且也希望在边缘处有刻度,你可以将 rcParams["axes.autolimit_mode"] (default: 'data') 切换为 'round_numbers'。这将轴的限制扩展到下一个整数值。

plt.rcParams['axes.autolimit_mode'] = 'round_numbers'

# Note: The limits are calculated at draw-time. Therefore, when using
# :rc:`axes.autolimit_mode` in a context manager, it is important that
# the ``show()`` command is within the context.

fig, ax = plt.subplots()
ax.scatter(x, y, c=x+y)
plt.show()
auto ticks

如果你使用 Axes.set_xmargin / Axes.set_ymargin 在数据周围设置额外的边距,仍然会遵守圆整数字的 autolimit_mode

fig, ax = plt.subplots()
ax.scatter(x, y, c=x+y)
ax.set_xmargin(0.8)
plt.show()
auto ticks

由 Sphinx-Gallery 生成的图库