简介
本实验旨在让你了解如何在 Matplotlib 中使用各种日期刻度定位器和格式化器。本教程将演示如何使用这些函数来定制具有时间数据的图表的 X 轴。
虚拟机使用提示
虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。
导入所需库
我们首先为本教程导入必要的库。我们将使用 matplotlib 和 numpy。
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.dates import (
FR, MO, MONTHLY, SA, SU, TH, TU, WE, AutoDateFormatter, AutoDateLocator,
ConciseDateFormatter, DateFormatter, DayLocator, HourLocator,
MicrosecondLocator, MinuteLocator, MonthLocator, RRuleLocator, SecondLocator,
WeekdayLocator, YearLocator, rrulewrapper)
import matplotlib.ticker as ticker
定义定位器和格式化器
我们定义将要使用的各种定位器和格式化器。此示例使用以下定位器:
AutoDateLocator(maxticks=8)YearLocator(month=4)MonthLocator(bymonth=[4, 8, 12])DayLocator(interval=180)WeekdayLocator(byweekday=SU, interval=4)HourLocator(byhour=range(0, 24, 6))MinuteLocator(interval=15)SecondLocator(bysecond=(0, 30))MicrosecondLocator(interval=1000)RRuleLocator(rrulewrapper(freq=MONTHLY, byweekday=(MO, TU, WE, TH, FR), bysetpos=-1))
以及以下格式化器:
AutoDateFormatter(ax.xaxis.get_major_locator())ConciseDateFormatter(ax.xaxis.get_major_locator())DateFormatter("%b %Y")
locators = [
('AutoDateLocator(maxticks=8)', '2003-02-01', '%Y-%m'),
('YearLocator(month=4)', '2003-02-01', '%Y-%m'),
('MonthLocator(bymonth=[4, 8, 12])', '2003-02-01', '%Y-%m'),
('DayLocator(interval=180)', '2003-02-01', '%Y-%m-%d'),
('WeekdayLocator(byweekday=SU, interval=4)', '2000-07-01', '%a %Y-%m-%d'),
('HourLocator(byhour=range(0, 24, 6))', '2000-02-04', '%H h'),
('MinuteLocator(interval=15)', '2000-02-01 02:00', '%H:%M'),
('SecondLocator(bysecond=(0, 30))', '2000-02-01 00:02', '%H:%M:%S'),
('MicrosecondLocator(interval=1000)', '2000-02-01 00:00:00.005', '%S.%f'),
('RRuleLocator(rrulewrapper(freq=MONTHLY, byweekday=(MO, TU, WE, TH, FR), '
'bysetpos=-1))', '2000-07-01', '%Y-%m-%d'),
]
formatters = [
'AutoDateFormatter(ax.xaxis.get_major_locator())',
'ConciseDateFormatter(ax.xaxis.get_major_locator())',
'DateFormatter("%b %Y")',
]
绘制图表
现在,我们可以创建图表了。我们将创建两个子图,分别展示定位器和格式化器的效果。对于每个定位器和格式化器,我们绘制一个图表,展示其对 X 轴的影响。我们使用 plot_axis 函数来实现这一点。该函数为每个轴设置通用参数,如脊柱(spines)、刻度参数和限制。它还为 X 轴设置定位器和格式化器。
def plot_axis(ax, locator=None, xmax='2002-02-01', fmt=None, formatter=None):
ax.spines[['left', 'right', 'top']].set_visible(False)
ax.yaxis.set_major_locator(ticker.NullLocator())
ax.tick_params(which='major', width=1.00, length=5)
ax.tick_params(which='minor', width=0.75, length=2.5)
ax.set_xlim(np.datetime64('2000-02-01'), np.datetime64(xmax))
if locator:
ax.xaxis.set_major_locator(eval(locator))
ax.xaxis.set_major_formatter(DateFormatter(fmt))
else:
ax.xaxis.set_major_formatter(eval(formatter))
ax.text(0.0, 0.2, locator or formatter, transform=ax.transAxes,
fontsize=14, fontname='Monospace', color='tab:blue')
fig, axs = plt.subplots(len(locators), 1, figsize=(8, len(locators) *.8),
layout='constrained')
fig.suptitle('Date Locators')
for ax, (locator, xmax, fmt) in zip(axs, locators):
plot_axis(ax, locator, xmax, fmt)
fig, axs = plt.subplots(len(formatters), 1, figsize=(8, len(formatters) *.8),
layout='constrained')
fig.suptitle('Date Formatters')
for ax, fmt in zip(axs, formatters):
plot_axis(ax, formatter=fmt)
显示图表
最后,我们可以使用 plt.show() 函数来显示图表。
plt.show()
总结
在本教程中,我们学习了如何在 Matplotlib 中使用各种日期刻度定位器和格式化器。我们绘制了几个图表,展示了每个定位器和格式化器如何影响带有时间数据的图表的 X 轴。这些知识在创建时间序列数据可视化时可能会很有用。