主次滴答声

演示如何使用主要和次要的断续器。

两个相关的类是 Locator S和 Formatter s、 定位器确定记号的位置,格式设置程序控制记号标签的格式。

默认情况下,“次要记号”处于禁用状态(使用 NullLocatorNullFormatter ). 通过设置次要定位器,可以在没有标签的情况下启用次要记号。可以通过设置次要格式设置工具来打开次要刻度标签。

MultipleLocator 将记号放在某个基数的倍数上。 StrMethodFormatter 使用格式字符串(例如。, '{{x:d}}''{{x:1.2f}}''{{x:1.1f}} cm' )要格式化记号标签(格式字符串中的变量必须是 'x' ). 为了一个 StrMethodFormatter ,字符串可以直接传递给 Axis.set_major_formatterAxis.set_minor_formatter . 合适的 StrMethodFormatter 将自动创建和使用。

pyplot.grid 同时更改y轴和y轴主记号的栅格设置。如果要控制给定轴的次记号的栅格,请使用例如:

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

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

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import (MultipleLocator, AutoMinorLocator)


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