我有一个大的多索引数据,我想要建立多个水平堆叠条形图使用的循环,但我不能正确的。
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)
但这不是我想要的。
我希望得到的是:
因为我的dataframe很大,所以我希望在for循环中这样做。有人能帮忙吗?谢谢。
发布于 2019-08-08 18:43:21
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()
输出:
发布于 2019-08-08 13:52:50
考虑循环第一个索引,字母,调用.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()
https://stackoverflow.com/questions/57416002
复制相似问题