2

I want to have a stacked bar chart which has the date as on X, a value on Y and a non-known number of values stacked on each other.

The table looks like that:

Date,Type,Value
2022-08-01,Type1,5000
2022-09-01,Type1,5500
2022-10-01,Type1,6000
2022-08-01,Type2,50000
2022-09-01,Type2,55000
2022-10-01,Type2,60000
2022-08-01,Type3,20000
2022-09-01,Type3,18000
2022-10-01,Type3,19000

So here, Type1, 2 and 3 would be stacked onto each other. I have seen examples of matplotlib with stacked=True, but this does not allow hue=Type. On the other hand, in seaborn, I use the hue parameter for types, but it does not have a stack bar version.

What is the easiest way to achieve this?

Hemmelig
  • 803
  • 10
  • 22

1 Answers1

2

Based on getup8 answer of Stacked bar chart in Seaborn you can do that by combining histplot with multiple='stack' and weights=.

weights : vector or key in data

If provided, weight the contribution of the corresponding data points towards the count in each bin by these factors.

enter image description here

Code:

import pandas as pd
import seaborn as sns

df = pd.DataFrame({
    'Date': ['2022-08-01', '2022-09-01', '2022-10-01', '2022-08-01', '2022-09-01', '2022-10-01', '2022-08-01', '2022-09-01', '2022-10-01'],
    'Type': ['Type1', 'Type1', 'Type1', 'Type2', 'Type2', 'Type2', 'Type3', 'Type3', 'Type3'],
    'Value': [5000, 5500, 6000, 50000, 55000, 60000, 20000, 18000, 19000]})


ax = sns.histplot(df, x='Date', hue='Type', weights='Value', multiple='stack')
MagnusO_O
  • 1,202
  • 4
  • 13
  • 19