Understand the idea
An annotation links text to a specific observation. Select the relevant row first so both coordinates describe the same point.
A small example
xy=(2, 70) points to that data location; xytext=(8, 8) with offset points places text a little right and above it.
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", ax=ax)
peak = df.loc[df["score"].idxmax()]
ax.annotate(
"Peak",
xy=(peak["hours"], peak["score"]),
xytext=(8, 8),
textcoords="offset points",
arrowprops={"arrowstyle": "->"},
)
ax.set(title="Study club", xlabel="hours", ylabel="score")
fig.tight_layout()
plt.show()What each part does
ax.annotate("Peak", xy=(x, y), ...)- label a point
idxmax()- row label of the largest value
arrowprops={"arrowstyle": "->"}- point an arrow at it
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, scatter hours against score.
- Label the row with highest score "Peak", offset by (8, 8) points, with an arrow.
- Chart: title "Study club"; x "hours"; y "score".
- Use: annotate().
Hint
Find the target row, then use both coordinates from that same row for the annotation.
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", ax=ax)
peak = df.loc[df["score"].idxmax()]
ax.annotate(
"Peak",
xy=(peak["hours"], peak["score"]),
xytext=(8, 8),
textcoords="offset points",
arrowprops={"arrowstyle": "->"},
)
ax.set(title="Study club", xlabel="hours", ylabel="score")
fig.tight_layout()
plt.show()