Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách vẽ Pandas multi-index DataFrame với tất cả xticks (Matplotlib)

Để vẽ Pandas multi-index data frame với tất cả xticks, ta thực hiện:

  • Thiết lập kích thước hình và điều chỉnh khoảng đệm giữa và xung quanh subplots.
  • Tạo giá trị index với 1000 mẫu dữ liệu.
  • Tạo ndarray một chiều với nhãn trục.
  • Lấy giá trị trung bình của series.
  • Vẽ dataframe g.
  • Đặt ticks và ticklabel trên trục hiện tại.
  • Hiển thị hình dùng show().

Ví dụ

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()

Kết quả

Cách vẽ Pandas multi-index DataFrame với tất cả xticks (Matplotlib)