用 Matplotlib 在轴标签中创建带日期和时间的图表


要使用轴标签中包含日期和时间的图形,我们可以执行以下步骤:

  • 创建一个图形并添加一组子图。
  • 使用 numpy 创建 x 和 y 数据点。
  • 设置 x 轴日期格式化程序。
  • 使用 plot() 方法绘制 x 和 y。
  • 设置 x 轴刻度。
  • 设置 x 轴的日期时间刻度标签,并旋转一定角度。
  • 使用 plt.tight_layout() 方法制作紧凑布局的图形。
  • 若要显示该图形,请使用 show() 方法。

示例

from matplotlib import pyplot as plt, dates
import datetime
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
x = np.array([datetime.datetime(2021, 1, 1, i, 0) for i in range(5)])
y = np.random.randint(5, size=x.shape)
ax.xaxis.set_major_formatter(dates.DateFormatter('%m-%d %H:%M'))
plt.plot(x, y)
ax.set_xticks(x)
ax.set_xticklabels(x, rotation=30, fontdict={'horizontalalignment': 'center'})
plt.show()

输出

更新于:2021 年 5 月 6 日

3K+ 次浏览

开启你的 职业生涯

完成课程,获得认证

开始学习
广告
© . All rights reserved.