Search code examples
pythonmatplotlibseabornbar-charthistogram

How to make a horizontal stacked histplot based on counts?


I have a df which represents three states (S1, S2, S3) at 3 timepoints (1hr, 2hr and 3hr). I would like to show a stacked bar plot of the states but the stacks are discontinous or at least not cumulative. How can I fix this in Seaborn? It is important that time is on the y-axis and the state counts on the x-axis.

enter image description here

Below is some code.

data = [[3, 2, 18],[4, 13, 6], [1, 2, 20]]
df = pd.DataFrame(data, columns = ['S1',  'S2', 'S3'])
df = df.reset_index().rename(columns = {'index':'Time'})
melt = pd.melt(df, id_vars = 'Time')

plt.figure()
sns.histplot(data = melt,x = 'value', y = 'Time', bins = 3, hue = 'variable', multiple="stack")

EDIT: This is somewhat what I am looking for, I hope this gives you an idea. Please ignore the difference in the scales between boxes...

enter image description here


Solution

  • If I understand correctly, I think you want to use value as a weight:

    sns.histplot(
        data=melt, y='Time', hue='variable', weights='value',
        multiple='stack', shrink=0.8, discrete=True,
    )
    

    enter image description here