I want to plot histogram and kde line in the same plot with different color. I want to set green color for the histogram and blue color for the kde line. I managed to figure out using line_kws to change the kde line color but hist_kws is not working on the displot. I have tried using histplot but I am unable to put different color for the hist and the line.
How to use hist_kws in seaborn displot
You can use line_kws={'color': ...}
to change the color of the kde line. And directly facecolor=...
to change the color of the histogram.
The following code has been tested with seaborn 0.11.1 and displot
with the default kind
(kind='hist')
and no hue
:
sns.displot(..., facecolor=...)
changes the color of the histogram facessns.displot(..., edgecolor=...)
changes the color of the histogram edgessns.displot(..., color=...)
changes the color of the kde line (whenkde=True
)sns.displot(..., line_kws={'lw':...})
changes the parameters of the kdeline, except the color
Here is an example:
import seaborn as sns
penguins = sns.load_dataset('penguins')
sns.displot(data=penguins, x="flipper_length_mm", kde=True, col="species", color='red',
line_kws={'lw': 3}, facecolor='lime', edgecolor='black')
Seaborn's forte is the hue
parameter, placing multiple distributions together, for which it is very handy that corresponding kde and histogram get the same color. When using hue
, the above coloring gets overridden.
Thank you very much for your help Johan. It works. May I know how do you figure it out? The arguments are not mentioned in sns documentation. I'm new to programming and I am aspire to be data scientist. –
Copartner
Seaborn creates some kind of chain with its parameters.
displot
names these kwargs
("keyword arguments") and says Other keyword arguments are documented with the relevant axes-level function. In this case they are sent to histplot
, which in its turn sends kwargs
to a.o. plt.bar
. –
Centavo @Centavo in which seaborn version you implemented the above code. I am using google colab and only facing issues regarding - changing the color of
kde
line. Line width etc everything working but only color is not changing. Please see this !image . Have tried so many different colors ! –
Penal @GirishKumarChandora It's unclear to me what went wrong. I updated the answer with code tested with seaborn 0.11.1. –
Centavo
hist_kws is an optional argument in distplot which takes only values in a dictionary. You can use this to set linewidth, edgecolor etc. Example for your ref
© 2022 - 2024 — McMap. All rights reserved.