Consider this dataframe:
data = {
'Categories': ['Opel', 'Audi', 'Lamborgini', 'McLaren'],
'Sale1': [60, 50, 40, 10],
'Sale2': [70, 10, 5, 30],
'Sale3': [5, 12, 20, 50],
'Month': [1, 1, 2, 2],
}
I was able to produce this by pivoting the table and adding a shift of the bar positions for each phase:
However my goal is to still have this grouped bar chart, however there should be 3 bars per category, and they should be stacked. So I can see tha month 1 and 2 proportions in each bar. How can I do this? If I dont shift them, they will overlap each other which is simialr to the stacking, but not quite the correct way to go.
Here is the code I wrote to do the above plot:
df = pd.DataFrame(data)
# Create a colormap with the desired colors for Month 1 and Month 2
colors_month1 = sns.color_palette("pastel", 3) # Use seaborn's "pastel" colormap for Month 1
colors_month2 = [(r, g, b, 0.2) for r, g, b in colors_month1] # Adjust alpha for Month 2
# Plot the bar chart
fig, ax = plt.subplots(figsize=(10, 6))
bar_width = 0.4
for i, month_group in df.groupby('Month'):
if i == 1:
colors = colors_month1
x_offset = 0
else:
colors = colors_month2
x_offset = bar_width # Shift the x positions for Month 2 bars to the right
month_group.pivot(index='Categories', columns='Month').plot.bar(
rot=0, ax=ax, width=bar_width, color=colors, position=x_offset
)