如何使用所有 xticks(Matplotlib)绘制 Pandas 多级索引 DataFrame?
要绘制带有所有 xticks 的 Pandas 多级索引数据框,我们可以执行以下步骤-
- 设置图形大小并调整子图之间和周围的填充。
- 创建带有 1000 个样本数据的索引值。
- 使用轴标签制作一维强数组。
- 获取序列的平均值。
- 绘制 g 数据框。
- 设置当前轴上的刻度和刻度标签。
- 使用 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()