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 · figures and composition · V31 · 8 MIN

Pair relationships

Explore several pairwise relationships in one figure.

Exercises within this concept

  1. FollowFollow the techniqueCurrent exercise
  2. ChangeAdapt a requirement
  3. TransferCombine earlier skills

Understand the idea

pairplot creates its own Figure: distributions on the diagonal and pairwise relationships off the diagonal.

Concept sketch: diagonal: distributions; off-diagonal: pairsxyxydiagonal: distributions; off-diagonal: pairs
Illustration · not the exercise output

A small example

For two variables, the grid shows each distribution and the relationship twice with swapped axes.

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

g = sns.pairplot(data=df, vars=["hours", "score"], hue="club", diag_kind="hist")
g.figure.tight_layout()
plt.show()

What each part does

g = sns.pairplot(...)
create a whole grid and keep its handle
vars=[...]
choose numeric columns
diag_kind="hist"
histogram on the diagonal
g.figure
the grid’s Figure

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, call pairplot for hours and score, hue=club, diag_kind="hist".
  2. This is a figure-level exception: do not create fig, ax first.
  3. Finish with g.figure.tight_layout() and plt.show().
Hint

pairplot owns its Figure; do not create an extra empty Figure first.

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

g = sns.pairplot(data=df, vars=["hours", "score"], hue="club", diag_kind="hist")
g.figure.tight_layout()
plt.show()
Your task · Follow
  1. Using df, call pairplot for hours and score, hue=club, diag_kind="hist".
  2. This is a figure-level exception: do not create fig, ax first.
  3. Finish with g.figure.tight_layout() and plt.show().

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.