0

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: enter image description here

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
    )
DPM
  • 845
  • 7
  • 33

1 Answers1

0

If I understand correctly, you are trying to stack the 3 bars for each manufacturer. To do this, it is much easier if you plot using pandas, which uses matplotlib under the hood. So, changing the plot line like this will give you the plot below.... Removed the .bar and moved it inside with kind='bar' and stacked=True

    month_group.pivot(index='Categories', columns='Month').plot(kind='bar', stacked=True,
        rot=0, ax=ax, width=bar_width, color=colors, position=x_offset
    )

This will give you the below plot...

enter image description here

Now, if you want both the bars not partially on top of each other, but next to each other instead, you will need to change x_offset=0 for the month 2 AND adjust the width as required using plt.xlim(-1,2) after plotting... you can adjust the -1 and 2 to make it more compact if you wish. The figure will look like this..

enter image description here

Redox
  • 9,321
  • 5
  • 9
  • 26