日期刻度标签#

Matplotlib 日期绘图是通过将日期实例转换为自纪元(默认情况下为 1970-01-01T00:00:00)以来的天数来完成的。matplotlib.dates 模块提供转换函数 date2numnum2date,它们将 datetime.datetimenumpy.datetime64 对象转换为 Matplotlib 的内部表示,反之亦然。这些数据类型在 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 分钟 1.733 秒)

Sphinx-Gallery 生成的图库