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 the palette=
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.
import seaborn as sns
titanic = sns.load_dataset('titanic')
sns.histplot(data=titanic, x='class', hue='alive', color=['navy', 'cornflowerblue'])
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)
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'})