主要和次要刻度#

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

两个相关的类是 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

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

由 Sphinx-Gallery 生成的画廊