日期刻度标签#

Matplotlib 日期绘图是通过将日期实例转换为自纪元以来的天数(默认为 1970-01-01T00:00:00)来完成的。该 matplotlib.dates模块提供转换器功能,并将date2num 对象与 Matplotlib 的内部表示进行转换。这些数据类型使用 中描述的单位转换机制注册 ,因此转换会自动为用户进行。注册过程还将轴的默认刻度和 设置为和 。num2datedatetime.datetimenumpy.datetime64matplotlib.unitslocatorformatterAutoDateLocatorAutoDateFormatter

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

DefaultFormatter、ConciseFormatter、手动 DateFormatter
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook

# 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', np_load=True)['price_data']

fig, axs = plt.subplots(3, 1, figsize=(6.4, 7), constrained_layout=True)
# 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.408秒)

由 Sphinx-Gallery 生成的画廊