Python 使用for循环的多个水平堆叠条形图

Python 使用for循环的多个水平堆叠条形图,python,for-loop,matplotlib,multi-index,stacked-chart,Python,For Loop,Matplotlib,Multi Index,Stacked Chart,我有一个大的多索引数据框,我想用for-loop构建多个水平堆叠条形图,但我没能把它做好 arrays = [['A', 'A', 'A','B', 'B', 'C', 'C'], ['red', 'blue', 'blue','purple', 'red', 'black', 'white']] df=pd.DataFrame(np.random.rand(7,4), index=pd.MultiIndex.from_arrays(arrays, names=('letter', 'col

我有一个大的多索引数据框,我想用for-loop构建多个水平堆叠条形图,但我没能把它做好

arrays = [['A', 'A', 'A','B', 'B', 'C', 'C'], 
['red', 'blue', 'blue','purple', 'red', 'black', 'white']]

df=pd.DataFrame(np.random.rand(7,4),
index=pd.MultiIndex.from_arrays(arrays, names=('letter', 'color')),
columns=["anna", "bill","david","diana"])
我试过:

fig, axs = plt.subplots(nrows=1, ncols=3, figsize=(10,10))
for ax, letter in zip(axs, ["A","B","C"]):
    ax.set_title(letter)
for name in ["anna","bill","david","diana"]:
    ax.barh(df.loc[letter][name], width=0.3)
但这不是我想要的

我希望得到的是:

  • 对于每个字母,都有一个水平堆叠条形图

  • 在每个图表中,颜色都列在y轴上

  • 值将按名称堆叠(因此名称是图例标签)


因为我的数据帧很大,所以我希望在for循环中完成这项工作。有人能帮忙吗?谢谢。

考虑在第一个索引字母上循环,调用
.loc
,它将第二个索引颜色作为循环数据帧的唯一索引,然后迭代调用
pandas.DataFrame.plot

fig, axs = plt.subplots(nrows=1, ncols=3, figsize=(10,10))

for ax, letter in zip(axs, ["A","B","C"]):
   df.loc[letter].plot(kind='barh', ax=ax, title=letter)
   ax.legend(loc='upper right')

plt.tight_layout()
plt.show()
plt.clf()
plt.close()

IIUC,请尝试以下操作:

grp = df.groupby(level=0)
fig, ax = plt.subplots(1, grp.ngroups, figsize=(10,10))
iax = iter(ax)

for n, g in grp:
    g.plot.barh(ax = next(iax), stacked = True, title = f'{n}')

plt.tight_layout()
输出: