如何在 Matplotlib 中在 X 軸上顯示日期和時間?


要在 Matplotlib 中在 X 軸上顯示日期和時間,我們可以採取以下步驟:

  • 設定圖形大小,並調整子圖之間和周圍的填充。
  • 建立一個 datesy 值的列表。
  • 獲取當前的座標軸。
  • 設定主要的日期格式和定位器。
  • 使用 plot() 方法繪製 xy 值。
  • 要顯示圖形,請使用 show() 方法。

示例

from datetime import datetime as dt
from matplotlib import pyplot as plt, dates as mdates

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

dates = ["01/02/2020", "01/03/2020", "01/04/2020"]
x_values = [dt.strptime(d, "%m/%d/%Y").date() for d in dates]
y_values = [1, 2, 3]
ax = plt.gca()

formatter = mdates.DateFormatter("%Y-%m-%d")
ax.xaxis.set_major_formatter(formatter)
locator = mdates.DayLocator()
ax.xaxis.set_major_locator(locator)
plt.plot(x_values, y_values)

plt.show()

輸出

更新於:08-Jul-2021

7K+ 瀏覽

開啟你的事業

完成課程並獲得認證

開始學習
廣告
© . All rights reserved.