首页 > 解决方案 > 使用 for 循环的多个水平堆积条形图

问题描述

我有一个大的多索引数据框,我想使用 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 循环中执行此操作。任何人都可以帮忙吗?谢谢。

标签: pythonfor-loopmatplotlibmulti-indexstacked-chart

解决方案


考虑循环第一个索引letter,调用将第二个索引color.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()

在此处输入图像描述


推荐阅读