多级(嵌套)刻度#

有时我们希望在轴上设置另一级的刻度标签,可能是为了指示刻度的分组。

Matplotlib 不提供自动实现此功能的方法,但在主轴下方进行标注相对简单。

这些示例使用Axes.secondary_xaxis,这是一种方法。它的优点是,如果需要,我们可以在用于分组的轴上使用 Matplotlib 的 Locators 和 Formatters。

第一个示例创建了一个辅助 x 轴,并使用Axes.set_xticks手动添加了刻度和标签。请注意,刻度标签开头带有一个换行符(例如" Oughts"),以便将第二级刻度标签置于主刻度标签下方。

import matplotlib.pyplot as plt
import numpy as np

import matplotlib.dates as mdates

rng = np.random.default_rng(19680801)

fig, ax = plt.subplots(layout='constrained', figsize=(4, 4))

ax.plot(np.arange(30))

sec = ax.secondary_xaxis(location=0)
sec.set_xticks([5, 15, 25], labels=['\nOughts', '\nTeens', '\nTwenties'])
multilevel ticks

第二个示例为分类轴添加了第二级标注。这里我们需要注意的是,每个动物(类别)都被分配了一个整数,所以cats在 x=0,dogs在 x=1,以此类推。然后我们将第二级的刻度放置在我们试图划分的动物类别中心的 x 值上。

此示例还在类别之间添加了刻度线,通过添加第二个辅助 x 轴,并在动物类别之间的边界处放置长而宽的刻度。

fig, ax = plt.subplots(layout='constrained', figsize=(7, 4))

ax.plot(['cats', 'dogs', 'pigs', 'snakes', 'lizards', 'chickens',
         'eagles', 'herons', 'buzzards'],
        rng.normal(size=9), 'o')

# label the classes:
sec = ax.secondary_xaxis(location=0)
sec.set_xticks([1, 3.5, 6.5], labels=['\n\nMammals', '\n\nReptiles', '\n\nBirds'])
sec.tick_params('x', length=0)

# lines between the classes:
sec2 = ax.secondary_xaxis(location=0)
sec2.set_xticks([-0.5, 2.5, 4.5, 8.5], labels=[])
sec2.tick_params('x', length=40, width=1.5)
ax.set_xlim(-0.6, 8.6)
multilevel ticks

日期是另一个我们可能需要第二级刻度标签的常见场景。在最后一个示例中,我们利用了向辅助 x 轴添加自动定位器和格式化器的能力,这意味着我们无需手动设置刻度。

此示例还与上述不同,我们将其放置在主轴下方的某个位置,即location=-0.075,然后通过将线宽设置为零来隐藏其边框。这意味着我们的格式化器不再需要前两个示例中的回车符。

fig, ax = plt.subplots(layout='constrained', figsize=(7, 4))

time = np.arange(np.datetime64('2020-01-01'), np.datetime64('2020-03-31'),
                 np.timedelta64(1, 'D'))

ax.plot(time, rng.random(size=len(time)))

# just format the days:
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d'))

# label the months:
sec = ax.secondary_xaxis(location=-0.075)
sec.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=1))

# note the extra spaces in the label to align the month label inside the month.
# Note that this could have been done by changing ``bymonthday`` above as well:
sec.xaxis.set_major_formatter(mdates.DateFormatter('  %b'))
sec.tick_params('x', length=0)
sec.spines['bottom'].set_linewidth(0)

# label the xaxis, but note for this to look good, it needs to be on the
# secondary xaxis.
sec.set_xlabel('Dates (2020)')

plt.show()
multilevel ticks

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

由 Sphinx-Gallery 生成的画廊