Understand the idea
savefig exports a specific Figure to a file. Finish the labels and layout before saving, then display it.
A small example
A 6 × 4 inch Figure at 150 dpi is about 900 × 600 pixels before tight cropping changes the edges.
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)
ax.set(title="Study club", xlabel="hours", ylabel="score")
fig.tight_layout()
fig.savefig("chart.png", dpi=150, bbox_inches="tight")
plt.show()What each part does
fig.savefig("chart.png", dpi=150, bbox_inches="tight")- export this Figure
.png- raster image format
dpi=150- pixels per inch
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, finish its title and labels, then save chart.png at 150 dpi with a tight bounding box before displaying.
- Use title "Study club", x label "hours", y label "score".
- Display the chart with plt.show().
- Use: savefig().
Hint
Save the explicit finished Figure before display, with the requested resolution.
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)
ax.set(title="Study club", xlabel="hours", ylabel="score")
fig.tight_layout()
fig.savefig("chart.png", dpi=150, bbox_inches="tight")
plt.show()