Introduction
You can use histplot()
from seaborn module to do the histogram plot. The following provides 3 examples. The following is the basic syntax of using histplot()
for the examples.
Example 1: Core syntax
sns.histplot(data=dataset, x=’column_name’)
Example 2: Group by the histogram
sns.histplot(data=dataset, x=’column_name’, hue=’column_groupby’)
Example 3: Add a kernel density estimate
sns.histplot(data=dataset, x=’column_name’, kde=True)
1. Example 1
The following provides a basic example of plotting histogram in Python. We use a built-in sample dataset called penguins in seaborn. We use the column of body weight as the focus for histogram.
import seaborn as sns
penguins = sns.load_dataset("penguins")
sns.histplot(data=penguins, x="body_mass_g")
Output:
The histogram above shows the count numbers for each weight for the penguins. Thus, by plotting it, it provides us insight how the weigtht distribution looks like.
2. Example 2: Group histogram based on another variable
There are 3 different species in the data. Thus, we can group the histogram based on species by adding the column name to the hue
.
# group the histogram based on species
sns.histplot(data=penguins,x="body_mass_g",hue='species')
Output:
3. Example 3: add a kernel density estimate to histogram
We can set kde
to be True to add a kernel density estimate to histogram.
sns.histplot(data=penguins,x="body_mass_g",hue='species',kde=True)
Output: