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
There are two misunderstandings:
color=
is ignored when working with hue. Instead, seaborn has thepalette=
parameter, which is much more versatile.palette
can be a name of colormap, a list of colors, or a dictionary.As mentioned by @TrentonMcKinney, by default the different hue values get layered transparently on top of each other (
multiple='layer'
).multiple='stack'
or multiple='dodge' will avoid overlapping bars. Further, you can set alpha=1 to get the full colors.This is what happens by default when the x-values are discrete. The bars are plotted transparently, and
color=
is ignored.Colors can be set via a
palette
, e.g.palette=['navy', 'cornflowerblue']
. To make sure which hue value gets which color, thepalette
can be a dictionary. Withmultiple='dodge'
, the bars are drawn next to each other.shrink=0.8
adds some spacing between the bars.multiple='stack'
stacks the bars.alpha=1
removes the transparency.