Home > other >  Re-order stacked histplot in Python's seaborn
Re-order stacked histplot in Python's seaborn

Time:10-21

I use Python's seaborn library and the histplot function to create a stacked barplot.

Here an example of how my data and the plot look:

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt


group = np.repeat(['G1', 'G2'], 4)
value = np.array(['1', '2', '3', '4', '1', '2', '3', '4'])
percentage = np.array([20, 10, 40, 30, 50, 25, 20, 5])
stacked = pd.DataFrame({'Group':group, 'Value':value, 'Percentage':percentage})
    
sns.histplot(stacked, x = 'Group', hue = 'Value', weights = 'Percentage', multiple = 'stack', palette = 'colorblind', shrink = 0.75)
plt.legend(labels = stacked['Value'].unique()[::-1], bbox_to_anchor = (1, 1), fontsize = 8)

this is how my current plot looks

I simply want to reverse the order of Value so that the blue part (1) is on bottom and the dark orange part (4) in on top. I.e., it should be ordered the same way as it is in the legend and the colors should stay the same (1 = blue, 2 = light orange and so on). Somehow, I can't manage to create this.

Any help is highly appreciated!

CodePudding user response:

You can use invert_yaxis and set yticks from 0 to 100 like below:

axe = sns.histplot(stacked, x = 'Group', hue = 'Value', weights = 'Percentage', multiple = 'stack', palette = 'colorblind', shrink = 0.75)
plt.legend(labels = stacked['Value'].unique()[::-1], bbox_to_anchor = (1, 1), fontsize = 8)
plt.gca().invert_yaxis()
plt.yticks(np.arange(0,100,20), np.arange(100,0,-20))
axe.margins(y=0)
plt.show()

If you add these lines you get this output:

enter image description here

  • Related