Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Data Foundations · A little practice goes a long way.

← Visualise lessonsTINY TABLES · REAL PYTHON · YOUR PACE
Optional · models and matrices · V23 · 8 MIN

Categorical / matrix heatmap

Prepare a matrix before colouring its cells.

Exercises within this concept

  1. FollowFollow the techniqueCurrent exercise
  2. ChangeAdapt a requirement
  3. TransferChoose and combine

Understand the idea

A heatmap colours the values you supply in a matrix. Choose whether each cell should count records or summarize a measurement.

Concept sketch: annotated counts for category pairsXYZA210B032annotated counts for category pairs
Illustration · not the exercise output

A small example

Two records in one category pair give count 2; if their ratings are 3 and 5, their mean rating is 4.

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 = pd.crosstab(df["club"], df["group"])
sns.heatmap(matrix, annot=True, fmt="d", cmap="Blues", ax=ax)
ax.set(title="Study club", xlabel="group", ylabel="club")
fig.tight_layout()
plt.show()

What each part does

matrix = pd.crosstab(...)
Count each club-and-group combination into a matrix.
sns.heatmap(matrix, ...)
Colour the counts in that matrix; it does not count the raw rows itself.
annot=True, fmt="d"
Print each integer count inside its cell.
cmap="Blues"
Use a light-to-dark blue colour scale.

Your inputs

The editable setup on the right creates df. Run executes the setup and your work from top to bottom.

Study club · 8 synthetic rows
studentclubhoursscoregroup
AriArt152A
BoCode371A
CyArt265B
DeeCode482B
EliArt589A
FloCode376A
GusArt693B
HanCode261B

Your task · Follow

  1. Using df, build a crosstab of club by group, then sns.heatmap with annot=True, fmt="d", cmap="Blues".
  2. Chart: title "Study club"; x "group"; y "club".
Hint

A category-count matrix and a measurement-average matrix answer different questions.

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 = pd.crosstab(df["club"], df["group"])
sns.heatmap(matrix, annot=True, fmt="d", cmap="Blues", ax=ax)
ax.set(title="Study club", xlabel="group", ylabel="club")
fig.tight_layout()
plt.show()
Your task · Follow
  1. Using df, build a crosstab of club by group, then sns.heatmap with annot=True, fmt="d", cmap="Blues".
  2. Chart: title "Study club"; x "group"; y "club".

Tab: indent · Shift+Tab: outdent · Esc, then Tab: leave editor

Edit Python. Control or Command plus Enter runs it. Tab indents by four spaces. Shift plus Tab outdents. Press Escape, then Tab or Shift plus Tab to leave the editor.

Each run executes all editor code in a fresh Python session. Display charts with plt.show().

Python starts when you open a lesson.

Output

Run your code to see what Python returns.