如何繪製包含所有 xticks 的 Pandas 多重索引資料框(Matplotlib)?


要繪製具有所有 xticks 的 Pandas 多重索引資料框,我們可以執行以下步驟 -

  • 設定圖形大小並調整子圖之間和周圍的邊距。
  • 使用 1000 個示例資料建立索引值。
  • 使用軸標籤建立一個一維ndarray
  • 獲取序列的平均值。
  • 繪製g資料框。
  • 在當前軸上設定 ticks 和 ticklabel
  • 要顯示圖形,請使用show()方法。

示例

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

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

idx = pd.date_range("2020-01-01", periods=1000)
val = np.random.rand(1000)
s = pd.Series(val, idx)

g = s.groupby([s.index.year, s.index.month]).mean()

ax = g.plot()
ax.set_xticks(range(len(g)))
ax.set_xticklabels(["%s-%02d" % item for item in g.index.tolist()],
rotation=45, ha='center')

plt.show()

輸出

更新時間:05-Jun-2021

4K+ 瀏覽

開啟你的職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.