Seaborn: kde_kws color specification failed in histplot()

Created on 10 Nov 2020  路  4Comments  路  Source: mwaskom/seaborn

I was trying to give the distribution KDE a different color when I use sns.histplot(),

Was thinking kde_kws = {'color': ...} would work, but it didn't.

sns.histplot(data=..., kde=True, kde_kws={"color": 'r'})

File ".../Python-library/seaborn/distributions.py", line 1422, in histplot
p.plot_univariate_histogram(
File ".../Python-library/seaborn/distributions.py", line 414, in plot_univariate_histogram
densities = self._compute_univariate_density(
File ".../Python-library/seaborn/distributions.py", line 283, in _compute_univariate_density
estimator = KDE(**estimate_kws)
TypeError: __init__() got an unexpected keyword argument 'color'

question

Most helpful comment

For anyone else who comes here in the future, I found the documentation slightly confusing, but the solution is easy. Assuming your data is x, you can just do something like:

sns.histplot(x, color='deepskyblue', stat='density')
sns.kdeplot(x, color='orange')

All 4 comments

The API docs say

kde_kws : dict

Parameters that control the KDE computation, as in kdeplot().

line_kws : dict

Parameters that control the KDE visualization, passed to matplotlib.axes.Axes.plot().

So you are using the wrong parameter.

But histplot does not allow you to use a different color for the histogram bars and the KDE line.

You can use histplot and kdeplot separately if you set the stat="density" in histplot.

For anyone else who comes here in the future, I found the documentation slightly confusing, but the solution is easy. Assuming your data is x, you can just do something like:

sns.histplot(x, color='deepskyblue', stat='density')
sns.kdeplot(x, color='orange')

Via sns.histplot(..., line_kws={'color': 'red', 'linewidth': 4, 'linestyle':':'}) you can change the aspects of the line, but the color gets overridden by the histogram's color (which is very useful there are multiple subsets; tested in seaborn 0.11.1). An idea could be to test whether 'color' or 'c' is present in line_kws and in that case not to pass the histogram's color.

slightly confusing me about kde_kws and line_kws

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vinay-jayaram picture vinay-jayaram  路  3Comments

amelio-vazquez-reina picture amelio-vazquez-reina  路  3Comments

ConstantinoSchillebeeckx picture ConstantinoSchillebeeckx  路  4Comments

btyukodi picture btyukodi  路  3Comments

bondarevts picture bondarevts  路  3Comments