colorsseabornhistplot

Set colors to hue categories


I'm trying to use sns.histplot() with 'hue' but the colors of the legend and the bars does not match. I would like to change the colors of the bars(blue, dark blue) to another, maybe the same as the legend.

How can I do that?

Here what I tried and did not work.

colors = sns.color_palette()
sns.histplot(data=dataset, x='contract', hue='churn', color=colors[:2])
plt.tight_layout()
plt.show()

And here what I got

enter image description here


Solution

  • There are two misunderstandings:

    This is what happens by default when the x-values are discrete. The bars are plotted transparently, and color= is ignored.

    import seaborn as sns
    
    titanic = sns.load_dataset('titanic')
    sns.histplot(data=titanic, x='class', hue='alive', color=['navy', 'cornflowerblue'])
    

    default histplot

    Colors can be set via a palette, e.g. palette=['navy', 'cornflowerblue']. To make sure which hue value gets which color, the palette can be a dictionary. With multiple='dodge', the bars are drawn next to each other. shrink=0.8 adds some spacing between the bars.

    sns.histplot(data=titanic, x='class', hue='alive', multiple='dodge',
                 palette={'no': 'navy', 'yes': 'cornflowerblue'}, shrink=0.8)
    

    sns.histplot with multiple='dodge'

    multiple='stack' stacks the bars. alpha=1 removes the transparency.

    sns.histplot(data=titanic, x='class', hue='alive', alpha=1, multiple='stack', shrink=0.8,
                 palette={'no': 'navy', 'yes': 'cornflowerblue'})
    

    sns.histplot with multiple='stack'