Reputation: 27
I have a following DataFrame:
from matplotlib import pyplot as plt
import pandas as pd
plotdata = pd.DataFrame({
"pies_2018":[40, 12, 10, 26, 36],
"pies_2019":[19, 8, 30, 21, 38],
"pies_2020":[10, 10, 42, 17, 37],
"pies_produced": [100, 80, 75, 10, 60]
},
index=["Dad", "Mam", "Bro", "Sis", "Me"]
)
plotdata.plot(kind="bar")
plt.title("Mince Pie Consumption Study Results")
plt.xlabel("Family Member")
plt.ylabel("Pies Consumed")
Now I'm looking for a way to plot a stacked bar chart, but I would like to stack only some series (pies_20*), and pies_produced should be presented next to stacked series, to show how consumed pies are compared to pies produced. So in the end I should get two bars for each family member. I don't want to sum pies_ *, because I still want to distinguish between consumption in time. See drawn example for Bro.
Would it be possible to show a legend with value for every year next to the stacked bar?
Thank you.
Upvotes: 1
Views: 429
Reputation: 150735
Try to plot twice with option stacked
and position
:
fig, ax = plt.subplots(figsize=(10,6))
# plot first 3 columns, stacked and shifted left
plotdata.iloc[:,:-1].plot.bar(stacked=True, position=1, width=.4, ax=ax)
# plot last column, shifted right
plotdata.iloc[:,-1:].plot.bar(position=0,color='C4', width=.4, ax=ax)
ax.set_xlim(-0.5, len(plotdata)-0.5)
Output:
Upvotes: 3