日期刻度标签#

Matplotlib 日期绘图是通过将日期实例转换为自纪元以来的天数(默认情况下为 1970-01-01T00:00:00)来完成的。matplotlib.dates 模块提供了转换器函数 date2numnum2date,用于在 Matplotlib 的内部表示形式之间转换 datetime.datetimenumpy.datetime64 对象。这些数据类型在 matplotlib.units 中描述的单位转换机制中注册,因此转换对用户来说是自动发生的。注册过程还为轴设置了默认的刻度 locatorformatter,分别为 AutoDateLocatorAutoDateFormatter

另一种格式化器是 ConciseDateFormatter,在下面的第二个 Axes 中使用(请参阅使用 ConciseDateFormatter 格式化日期刻度),它通常无需旋转刻度标签。最后一个 Axes 使用 DateFormatter 手动格式化日期,使用 datetime.date.strftime 中记录的格式字符串格式化日期。

DefaultFormatter, ConciseFormatter, Manual DateFormatter
import matplotlib.pyplot as plt

import matplotlib.cbook as cbook
import matplotlib.dates as mdates

# Load a numpy record array from yahoo csv data with fields date, open, high,
# low, close, volume, adj_close from the mpl-data/sample_data directory. The
# record array stores the date as an np.datetime64 with a day unit ('D') in
# the date column.
data = cbook.get_sample_data('goog.npz')['price_data']

fig, axs = plt.subplots(3, 1, figsize=(6.4, 7), layout='constrained')
# common to all three:
for ax in axs:
    ax.plot('date', 'adj_close', data=data)
    # Major ticks every half year, minor ticks every month,
    ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=(1, 7)))
    ax.xaxis.set_minor_locator(mdates.MonthLocator())
    ax.grid(True)
    ax.set_ylabel(r'Price [\$]')

# different formats:
ax = axs[0]
ax.set_title('DefaultFormatter', loc='left', y=0.85, x=0.02, fontsize='medium')

ax = axs[1]
ax.set_title('ConciseFormatter', loc='left', y=0.85, x=0.02, fontsize='medium')
ax.xaxis.set_major_formatter(
    mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))

ax = axs[2]
ax.set_title('Manual DateFormatter', loc='left', y=0.85, x=0.02,
             fontsize='medium')
# Text in the x-axis will be displayed in 'YYYY-mm' format.
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
# Rotates and right-aligns the x labels so they don't crowd each other.
for label in ax.get_xticklabels(which='major'):
    label.set(rotation=30, horizontalalignment='right')

plt.show()

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

Sphinx-Gallery 生成的图库