You can use the hue parameter when creating histograms in seaborn to color the bars in the histogram based on the value of some specific variable.
You can use the following basic syntax to do so:
import seaborn as sns sns.histplot(data=df, x='points', hue='team')
This particular example creates a histogram for the variable points in which the bars are colored based on the value of the team variable.
The following example shows how to use this syntax in practice.
Example: Using hue Parameter in Seaborn Histogram
Suppose we have the following pandas DataFrame that shows the points scored by basketball players on two different teams:
import pandas as pd
import numpy as np
#make this example reproducible
np.random.seed(1)
#create DataFrame
df = pd.DataFrame({'team':np.repeat(['A', 'B'], 100),
'points': np.concatenate([
np.random.normal(size=100,loc=15,scale=2),
np.random.normal(size=100, loc=25, scale=4)])})
#view head of DataFrame
print(df.head())
team points
0 A 18.248691
1 A 13.776487
2 A 13.943656
3 A 12.854063
4 A 16.730815
We can use the seaborn histplot() function with the hue parameter to create histograms of the points variable, grouped by the team variable:
import seaborn as sns
#create histogram to visualize distribution of points by team
sns.histplot(data=df, x='points', hue='team')
The resulting plot contains overlapping histograms whose colors are based on the values in the team column.
Note that we can also use the palette argument to specify the colors to be used in the histogram:
import seaborn as sns
#create histogram to visualize distribution of points by team
sns.histplot(data=df, x='points', hue='team', palette=['lightgreen', 'pink'])
The two histograms now use light green and pink as the colors, just as we specified using the palette argument in the histplot() function.
Note: You can find the complete documentation for the seaborn histplot() function here.
Additional Resources
The following tutorials explain how to perform other common tasks using seaborn:
How to Add a Title to Seaborn Plots
How to Change Font Size in Seaborn Plots
How to Adjust Number of Ticks in Seaborn Plots