Dataset
For a barplot, we need a dataset with 3 columns: one for the main categories, one for the sub categories and one for the values.
Let's create it using pandas:
| A | X | 17 |
| A | Y | 10 |
| B | X | 42 |
| B | Y | 22 |
| C | X | 33 |
Stacked Barplot with plotly express
The chart is made using using the bar() function from the plotly.express module.
We just have to pass the df object, and specify which column we want to plot. In this case it's the category and the value (defined above).
Then we just need to specify the color argument with the sub_category column so that colors map this column.
Now we save it as an html element in order to render it
Barplot with plotly graph object
The plotly graph object API requires a bit more verbose, but nothing very complex here!
We mainly have to iterate over each sub categories, filter the dataframe on this sub category, and plot it.
Last but not least, we use the update_layout() function with the barmode='stack' argument to ensure that bars are stacked on each others. Otherwise the default render will put them next to each other (the default value is group)
Now we save it as an html element in order to render it