Understand the idea
A correlation heatmap colours a matrix of pairwise numeric relationships. Keep a fixed colour scale so colours retain the same meaning.
A small example
A cell at row hours and column score contains their correlation. The mirrored score–hours cell contains the same value.
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))
matrix = df.corr(numeric_only=True)
sns.heatmap(matrix, annot=True, vmin=-1, vmax=1, center=0, cmap="vlag", ax=ax)
ax.set(title="Study club", xlabel="Variable", ylabel="Variable")
fig.tight_layout()
plt.show()What each part does
df.corr(numeric_only=True)- prepare the matrix
annot=True- print cell values
vmin=-1, vmax=1, center=0- meaningful colour limits
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 sns.heatmap of numeric correlations with annot=True, vmin=-1, vmax=1, center=0 and cmap="vlag".
- Chart: title "Study club"; x "Variable"; y "Variable".
Hint
Build a correlation matrix first, then keep the colour scale fixed from -1 to 1.
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))
matrix = df.corr(numeric_only=True)
sns.heatmap(matrix, annot=True, vmin=-1, vmax=1, center=0, cmap="vlag", ax=ax)
ax.set(title="Study club", xlabel="Variable", ylabel="Variable")
fig.tight_layout()
plt.show()