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

multiple horizontal stacked bar charts using for loop

我有一个大的多索引数据框,我想使用 for 循环构建多个水平堆叠条形图,但我做不对。

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)

但这不是我想要的

我希望得到的是:

由于我的数据框很大,我希望在for循环中执行此操作。谁能帮忙?谢谢

考虑遍历第一个索引 letter,调用 .loc 呈现第二个索引 color,作为唯一索引循环数据帧然后迭代调用 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()

输出: