如何更改 Matplotlib 圖表的日期時間刻度標註頻率?


要更改 Matplotlib 圖表的日期時間刻度標註頻率,我們可以建立一個數據框,並在某個日期範圍內繪製它們

步驟

  • 設定圖形大小並調整子圖之間及周圍的填充。
  • 使用 Pandas 資料框建立潛在異構表格資料。
  • 使用 plot() 方法繪製資料框。
  • 設定 X 軸主要定位器,即 刻度。
  • 設定 X 軸主要的格式化程式,即 刻度標籤。
  • 使用 autofmt_xdate()。日期刻度標註經常重疊,因此將它們旋轉並右對齊是有用的。
  • 使用 show() 方法顯示圖形。

示例

import pandas as pd
import numpy as np

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

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

index = pd.date_range(start="2020-07-01", end="2021-01-01", freq="D")
index = [pd.to_datetime(date, format='%Y-%m-%d').date() for date in index]

data = np.random.randint(1, 100, size=len(index))

df = pd.DataFrame(data=data, index=index, columns=['data'])

ax = df.plot()
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))

plt.gcf().autofmt_xdate()

plt.show()

輸出

更新於:2021 年 6 月 17 日

5K+ 次瀏覽

開啟你的 職業生涯

完成課程後即可獲得認證

立即開始
廣告