I have a big multi-index dataframe, and I would like to build multiple horizontal stacked bar charts using for loop, but I couldn't get it right.
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"])
I have tried:
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)
But this is not what I want.
What I hope to get is:
for each letter, there is a horizontal stacked bar chart
in each chart, colors are listed on y axis
values will be stacked by names (so names are the legend labels)
Since my dataframe is big, I hope to do this in a for loop. Can anyone help? Thanks.