Grouping and Hue for Comparisons in Seaborn
One of Seaborn’s most powerful features is its ability to easily compare subgroups within a dataset using the hue
parameter.
By adding hue
, you can split data into categories and display them with different colors — making comparisons more intuitive.
Why Hue is Useful
- Adds another layer of information without creating separate plots.
- Helps identify patterns and differences between categories.
- Works across most Seaborn functions like
barplot
,scatterplot
, andlineplot
.
Example – Comparing Categories in a Scatterplot
Scatterplot with Hue
import seaborn as sns
import matplotlib.pyplot as plt
# Sample dataset
tips = sns.load_dataset("tips")
# Scatterplot with hue for gender
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="sex")
plt.title("Total Bill vs Tip by Gender")
plt.show()
hue="sex"
automatically assigns different colors for male and female groups.- Seaborn adds a legend by default to indicate which color corresponds to which group.
Pro Tip
When using hue
, you can also adjust palette for custom color schemes:
Custom Color Palette
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="sex", palette="Set2")
In the next Jupyter notebook, you’ll explore how to use hue
in different chart types and experiment with your own datasets.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.