Understand the idea
subplots creates several plotting areas on one Figure. Send each chart to its intended Axes.
A small example
subplots(1, 2) creates left and right panels; subplots(2, 1) creates upper and lower panels.
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, axes = plt.subplots(1, 2, figsize=(10, 4))
sns.histplot(data=df, x="hours", bins=4, ax=axes[0])
sns.scatterplot(data=df, x="hours", y="score", ax=axes[1])
axes[0].set(title="Distribution", xlabel="hours", ylabel="Count")
axes[1].set(title="Relationship", xlabel="hours", ylabel="score")
fig.tight_layout()
plt.show()What each part does
fig, axes = plt.subplots(1, 2, figsize=(10, 4))- two plotting areas
axes[0]- first Axes
ax=axes[1]- draw on the second Axes
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, create a two-panel Figure: a 4-bin histogram of hours on the left and a scatter of hours against score on the right.
- Use panel titles "Distribution" and "Relationship", x labels "hours", and y labels "Count" and "score".
- Finish the Figure with tight_layout and show.
- Use: subplots().
Hint
Pass each chart its own axes[0] or axes[1]; finish the whole Figure once.
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, axes = plt.subplots(1, 2, figsize=(10, 4))
sns.histplot(data=df, x="hours", bins=4, ax=axes[0])
sns.scatterplot(data=df, x="hours", y="score", ax=axes[1])
axes[0].set(title="Distribution", xlabel="hours", ylabel="Count")
axes[1].set(title="Relationship", xlabel="hours", ylabel="score")
fig.tight_layout()
plt.show()