Pair plots

pairplot for every numeric column against the others.

sns.pairplot draws every numeric column against every other numeric column: scatter off-diagonal, histograms (or KDE) on the diagonal. hue colors the points.

Goal

Build a three-column frame and draw a pairplot, then hue by city.

All numeric pairs

rng = np.random.default_rng(0)
n = 60
df = pd.DataFrame(
    {
        "units": rng.integers(1, 20, size=n),
        "price": rng.choice([10.5, 22.0], size=n),
    }
)
df["revenue"] = df["units"] * df["price"] + rng.normal(0, 8, size=n)
sns.pairplot(df)
plt.show()

Hue

rng = np.random.default_rng(0)
n = 70
df = pd.DataFrame(
    {
        "city": rng.choice(["Nairobi", "Mombasa", "Kisumu"], size=n),
        "units": rng.integers(1, 20, size=n),
        "price": rng.choice([10.5, 22.0], size=n),
    }
)
df["revenue"] = df["units"] * df["price"]
sns.pairplot(df, hue="city", corner=True)
plt.show()

corner=True draws only the lower triangle so the figure is smaller.

Vars subset

rng = np.random.default_rng(1)
n = 50
df = pd.DataFrame(
    {
        "city": rng.choice(["Nairobi", "Mombasa"], size=n),
        "units": rng.integers(1, 20, size=n),
        "price": rng.choice([10.5, 22.0, 31.0], size=n),
        "cost": rng.uniform(4, 12, size=n),
    }
)
df["revenue"] = df["units"] * df["price"]
sns.pairplot(df, vars=["units", "revenue", "cost"], hue="city")
plt.show()

Pairplot is slow with dozens of numeric columns. Pass vars= to keep three or four.

Pitfall

pairplot is figure-level. Still call plt.show(). A 12-row table makes a sparse scatter — generate more rows as in this chapter.