python - 使用 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)
但这不是我想要的。
我希望得到的是:
对于每个字母,都有一个水平堆积条形图
在每个图表中,颜色列在 y 轴上
值将按名称堆叠(因此名称是图例标签)
由于我的数据框很大,我希望在 for 循环中执行此操作。任何人都可以帮忙吗?谢谢。
解决方案
考虑循环第一个索引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()
推荐阅读
- angular - Nativescript procudes bootstrap: StaticInjectorError(AppModule)[EffectSources -> ErrorHandler]:
- sed - 如何在不使用 sed 在保持空间中插入新行的情况下从模式空间追加到保持空间?
- asp.net-mvc - 选择不按它们被选择的顺序出现 - Select2 js
- node.js - index.ejs 与 index.html
- android - android上的离子运行停止工作
- git - 如何区分多分支构建中的快照?
- vba - 用于创建周列的公式或 VBA
- android - 画布绘图只占屏幕的 1/3
- javascript - youtube 自动播放不起作用
- python - 项目目录的Python文件夹结构和轻松导入