I am creating a histrogram (frecuency vs. count) and I want to add kernel density estimate line in a different colour. How can I do this? I want to change the colour for example
sns.histplot(data=penguins, x="flipper_length_mm", kde=True)
Example taken from https://seaborn.pydata.org/generated/seaborn.histplot.html
histplot
's line_kws={...}
is meant to change the appearance of the kde line. However, the current seaborn version doesn't allow changing the color that way, probably because the color goes together with the hue
parameter (although hue
isn't used in this case).
import seaborn as sns
penguins = sns.load_dataset('penguins')
ax = sns.histplot(data=penguins, x="flipper_length_mm", kde=True,
line_kws={'color': 'crimson', 'lw': 5, 'ls': ':'})
In seaborn's github, it is suggested to draw the histplot
and the kdeplot
separately. For both to match in the y-direction, it is necessary to use histplot
with stat='density'
(the kdeplot
doesn't have a parameter to use histplot
's default stat='count'
).
penguins = sns.load_dataset('penguins')
ax = sns.histplot(data=penguins, x="flipper_length_mm", kde=False, stat='density')
sns.kdeplot(data=penguins, x="flipper_length_mm", color='crimson', ax=ax)
If the count
statistics is really needed, an alternative is to change the line color via matplotlib:
penguins = sns.load_dataset('penguins')
ax = sns.histplot(data=penguins, x="flipper_length_mm", kde=True)
ax.lines[0].set_color('crimson')