Skip to content
Advertisement

How to have clusters of stacked bars

So here is how my data set looks like :

JavaScript

I want to have stacked bar plot for each dataframe but since they have same index, I’d like to have 2 stacked bars per index.

I’ve tried to plot both on the same axes :

JavaScript

But it overlaps.

Then I tried to concat the two dataset first :

JavaScript

but here everything is stacked

My best try is :

JavaScript

Which gives :

enter image description here

This is basically what I want, except that I want the bar ordered as

(df1,A) (df2,A) (df1,B) (df2,B) etc…

I guess there is a trick but I can’t found it !


After @bgschiller’s answer I got this :

enter image description here

Which is almost what I want. I would like the bar to be clustered by index, in order to have something visually clear.

Bonus : Having the x-label not redundant, something like :

JavaScript

Advertisement

Answer

I eventually found a trick (edit: see below for using seaborn and longform dataframe):

Solution with pandas and matplotlib

Here it is with a more complete example :

JavaScript

And it gives that :

multiple stacked bar plot

You can change the colors of the bar by passing a cmap argument:

JavaScript

Solution with seaborn:

Given the same df1, df2, df3, below, I convert them in a long form:

JavaScript

The problem with seaborn is that it doesn’t stack bars natively, so the trick is to plot the cumulative sum of each bar on top of each other:

JavaScript

Then loop over each group of variable and plot the cumulative sum:

JavaScript

multiple stack bar plot seaborn

It lacks the legend that can be added easily I think. The problem is that instead of hatches (which can be added easily) to differentiate the dataframes we have a gradient of lightness, and it’s a bit too light for the first one, and I don’t really know how to change that without changing each rectangle one by one (as in the first solution).

Tell me if you don’t understand something in the code.

Feel free to re-use this code which is under CC0.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement