You can use the hue parameter when creating pairplots in seaborn to color plot aspects based on the values of a specific variable.
You can use the following basic syntax:
import seaborn as sns sns.pairplot(data=df, hue='team')
This particular example creates a pairplot using every numerical variable in the data frame and colors the plot aspects 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 Pairplot
Suppose we have the following pandas DataFrame that shows the points and assists by basketball players on two different teams:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
'assists': [3, 4, 4, 7, 9, 6, 7, 8, 10, 12],
'points': [5, 6, 9, 12, 15, 5, 10, 13, 13, 19]})
#view DataFrame
print(df)
team assists points
0 A 3 5
1 A 4 6
2 A 4 9
3 A 7 12
4 A 9 15
5 B 6 5
6 B 7 10
7 B 8 13
8 B 10 13
9 B 12 19
If we use the pairplot() function, then seaborn will create a pairplot using the two numerical variables in the DataFrame:
import seaborn as sns
#create pairplot
sns.pairplot(data=df)
The resulting pairplot displays scatterplots and histograms using the points and assists variables.
If we use the hue parameter within the pairplot() function, we can color the aspects of the plot based on the values of the team variable:
import seaborn as sns
#create pairplot using values of team variable as colors
sns.pairplot(data=df, hue='team')
By using the hue parameter, we’re able to make the following changes in the plot:
- The points in the scatterplot are colored based on the team value.
- Overlapping density curves are used to visualize the distribution of values for each unique team.
Notice that a legend is also automatically added so that we know which colors correspond to which team values.
Note: You can find the complete documentation for the seaborn pairplot() 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