用 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+ 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告