Understand the idea
A legend explains how appearance maps to data. Use distinct shapes alongside colour so group identity remains readable without colour.
A small example
With hue and style both mapped to group, each group gets a colour and a marker shape in the legend.
Follow the code
Apply the idea to the supplied table. Read from top to bottom; the final line displays the result.
import matplotlib.pyplot as plt
import seaborn as sns
fig, ax = plt.subplots(figsize=(6, 4))
sns.scatterplot(
data=df, x="hours", y="score", hue="club", style="club", palette="colorblind", ax=ax
)
ax.legend(title="Category")
ax.set(title="Study club", xlabel="hours", ylabel="score")
fig.tight_layout()
plt.show()What each part does
palette="colorblind"- a palette designed for categorical separation
ax.legend(title=...)- label the category key
style=- another cue alongside hue
Other choices for later exercises
hue_order=[...]- consistent category order across charts
alpha=0.6- partial transparency reveals overlapping points
Your inputs
The editable setup on the right creates df. Run executes the setup and your work from top to bottom.
| student | club | hours | score | group |
|---|---|---|---|---|
| Ari | Art | 1 | 52 | A |
| Bo | Code | 3 | 71 | A |
| Cy | Art | 2 | 65 | B |
| Dee | Code | 4 | 82 | B |
| Eli | Art | 5 | 89 | A |
| Flo | Code | 3 | 76 | A |
| Gus | Art | 6 | 93 | B |
| Han | Code | 2 | 61 | B |
Your task · Follow
- Using df, plot hours against score with sns.scatterplot, hue=club, style=club and palette="colorblind".
- Set the legend title to "Category".
- Chart: title "Study club"; x "hours"; y "score".
Hint
A legend describes the mapped category; redundant shapes help when colour is insufficient.
Reveal solution
One way to do it. Keep any supplied setup in the editor and use this in the Your work section.
import matplotlib.pyplot as plt
import seaborn as sns
fig, ax = plt.subplots(figsize=(6, 4))
sns.scatterplot(
data=df, x="hours", y="score", hue="club", style="club", palette="colorblind", ax=ax
)
ax.legend(title="Category")
ax.set(title="Study club", xlabel="hours", ylabel="score")
fig.tight_layout()
plt.show()