Manolo Dominguez Becerra
Manolo Dominguez Becerra

Reputation: 1373

How to modify the kernel density estimate line in a sns.histplot

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)

enter image description here

Example taken from https://seaborn.pydata.org/generated/seaborn.histplot.html

Upvotes: 7

Views: 12747

Answers (1)

JohanC
JohanC

Reputation: 80449

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': ':'})

histplot changing kde line parameters

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)

sns.histplot and sns.kdeplot separately

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')

changing line color of sns.histplot with kde=True

Upvotes: 24

Related Questions