gpt4 book ai didi

python - 使用 Pandas MultiIndex 在 matplotlib 条形图中对标签进行分组

转载 作者:太空狗 更新时间:2023-10-30 02:20:29 27 4
gpt4 key购买 nike

我有一个带有 MultiIndex 的 pandas DataFrame:

group   subgroup    obs_1    obs_2
GroupA Elem1 4 0
Elem2 34 2
Elem3 0 10
GroupB Elem4 5 21

等等。如 this SO question 中所述这在 matplotlib 中实际上是可行的,但我宁愿(如果可能的话)使用我已经知道层次结构的事实(多亏了 MultiIndex)。目前发生的情况是索引显示为元组。

这样的事情可能吗?

最佳答案

如果 MultiIndex 中只有两层,我相信下面的操作会更简单:

plt.figure()
ax = plt.gca()
DF.plot(kind='bar', ax=ax)
plt.grid(True, 'both')
minor_XT = ax.get_xaxis().get_majorticklocs()
DF['XT_V'] = minor_XT
major_XT = DF.groupby(by=DF.index.get_level_values(0)).first()['XT_V'].tolist()
DF.__delitem__('XT_V')
ax.set_xticks(minor_XT, minor=True)
ax.set_xticklabels(DF.index.get_level_values(1), minor=True)
ax.tick_params(which='major', pad=15)
_ = plt.xticks(major_XT, (DF.index.get_level_values(0)).unique(), rotation=0)

enter image description here

还有一些涉及但更通用的解决方案(无论您有多少级别):

def cvt_MIdx_tcklab(df):
Midx_ar = np.array(df.index.tolist())
Blank_ar = Midx_ar.copy()
col_idx = np.arange(Midx_ar.shape[0])
for i in range(Midx_ar.shape[1]):
val,idx = np.unique(Midx_ar[:, i], return_index=True)
Blank_ar[idx, i] = val
idx=~np.in1d(col_idx, idx)
Blank_ar[idx, i]=''
return map('\n'.join, np.fliplr(Blank_ar))

plt.figure()
ax = plt.gca()
DF.plot(kind='bar', ax=ax)
ax.set_xticklabels(cvt_MIdx_tcklab(DF), rotation=0)

关于python - 使用 Pandas MultiIndex 在 matplotlib 条形图中对标签进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22780563/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com