Control rug and density on a Seaborn histogram

logo of a chart:Histogram

By default, the hisplot function of Seaborn plots an histogram without a density curve (see histogram with seaborn). You can easily add the latter by setting the kde argument to True. You can also control the presence of rugs using rug=True. You can customize rug and density as presented below.

Libraries & Dataset

First, we need to load a few libraries and the iris dataset:

# libraries
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="darkgrid")

# dataset
df = sns.load_dataset("iris")

Histogram + rug + kernel density curve

Rugs are small lines or marks at the edge of a plot that represent the distribution of individual data points along an axis.

sns.displot(data=df["sepal_length"], kde=True, rug=True)
plt.show()

Customizing rugs

Thanks to the rug_kws argument, we can easily change how the rugs look like!

sns.displot(df["sepal_length"],
            kde=True,
            rug=True,
            rug_kws={"alpha": 0.2, "linewidth": 4, "height": 0.2})
plt.show()

Customizing the density curve

It's also pretty straight forward to customize the density curve in a chart:

sns.displot(df["sepal_length"],
            kind="kde",
            fill=True,
            rug=True,
            rug_kws={"alpha": 0.9, "height": 0.1},
            color="skyblue",
            alpha=0.6,)
plt.show()

Going further

This post explains how to customize a distribution plot by adding rugs and density to it using seaborn!

For more examples of how to create or customize your distribution plots, see the density plot section. You may also be interested in how to create a density chart with multiple groups.

Contact & Edit


👋 This document is a work by Yan Holtz. You can contribute on github, send me a feedback on twitter or subscribe to the newsletter to know when new examples are published! 🔥

This page is just a jupyter notebook, you can edit it here. Please help me making this website better 🙏!