主刻度和次刻度#

演示如何使用主要和次要刻度。

两个相关的类是 LocatorFormatter。Locator 决定刻度的位置,而 Formatter 控制刻度标签的格式。

次刻度默认关闭(使用 NullLocatorNullFormatter)。可以通过设置次刻度定位器来打开次刻度而不显示标签。可以通过设置次刻度格式化器来打开次刻度标签。

MultipleLocator 在某个基数的倍数上放置刻度。StrMethodFormatter 使用格式字符串(例如,'{x:d}''{x:1.2f}''{x:1.1f} cm')来格式化刻度标签(格式字符串中的变量必须是 'x')。对于 StrMethodFormatter,字符串可以直接传递给 Axis.set_major_formatterAxis.set_minor_formatter。一个适当的 StrMethodFormatter 将被自动创建并使用。

pyplot.grid 同时更改 x 轴和 y 轴主刻度的网格设置。如果你想控制给定轴次刻度的网格,可以使用例如

ax.xaxis.grid(True, which='minor')

请注意,给定的定位器或格式化实例只能用于单个轴(因为定位器存储了对轴数据和视图限制的引用)。

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.ticker import AutoMinorLocator, MultipleLocator

t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1 * np.pi * t) * np.exp(-t * 0.01)

fig, ax = plt.subplots()
ax.plot(t, s)

# Make a plot with major ticks that are multiples of 20 and minor ticks that
# are multiples of 5.  Label major ticks with '.0f' formatting but don't label
# minor ticks.  The string is used directly, the `StrMethodFormatter` is
# created automatically.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.xaxis.set_major_formatter('{x:.0f}')

# For the minor ticks, use no labels; default NullFormatter.
ax.xaxis.set_minor_locator(MultipleLocator(5))

plt.show()
major minor demo

自动选择主刻度和次刻度。

使用交互式的平移和缩放来查看刻度间隔如何变化。每个主要间隔将会有4或5个次要刻度间隔,具体取决于主要间隔。

可以向 AutoMinorLocator 提供一个参数,以指定每个主区间内的次区间固定数量,例如 AutoMinorLocator(2) 会在主刻度之间产生一个次刻度。

t = np.arange(0.0, 100.0, 0.01)
s = np.sin(2 * np.pi * t) * np.exp(-t * 0.01)

fig, ax = plt.subplots()
ax.plot(t, s)

ax.xaxis.set_minor_locator(AutoMinorLocator())

ax.tick_params(which='both', width=2)
ax.tick_params(which='major', length=7)
ax.tick_params(which='minor', length=4, color='r')

plt.show()
major minor demo

由 Sphinx-Gallery 生成的图库