Pair plots and PCA¶
A figure shows two columns of a table easily, and a dataset often has more columns. This notebook plots a table with four number columns in two ways. A pair plot draws every pair of columns. Principal component analysis (PCA) turns the four columns into two, so that one scatter plot shows all of them.
Sections: Load the iris data, Pair plot, Pair plot with color, Dimension reduction with PCA.
Packages beyond the standard library: matplotlib, pandas, seaborn, scikit-learn.
Install them with uv add matplotlib pandas seaborn scikit-learn (or pip install).
Colab already has all four.
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
Load the iris data¶
The data is the iris data: four measurements, in centimeters, of 150 iris flowers of three
species. R. A. Fisher published the measurements in 1936
(Fisher, 1936). The cell downloads the
file iris.csv from the repository of the seaborn example data,
mwaskom/seaborn-data, at a fixed commit.
IRIS_URL = (
"https://raw.githubusercontent.com/mwaskom/seaborn-data/"
"71e2436a092d714350de0fc409ca8a8714e7e78f/iris.csv"
)
iris = pd.read_csv(IRIS_URL)
iris
The table has 150 rows, one for each flower, and 5 columns.
Four columns are measurements: the length and the width of a sepal, and the length and the width of a petal.
The sepals are the outer parts of the flower, and the petals are the inner parts.
The fifth column is the species: setosa, versicolor, or virginica, with 50 flowers each.
| sepal_length | sepal_width | petal_length | petal_width | species | |
|---|---|---|---|---|---|
| 0 | 5.1 | 3.5 | 1.4 | 0.2 | setosa |
| 1 | 4.9 | 3.0 | 1.4 | 0.2 | setosa |
| ... | ... | ... | ... | ... | ... |
| 149 | 5.9 | 3.0 | 5.1 | 1.8 | virginica |
Pair plot¶
A pair plot draws every pair of columns.
Off the diagonal, each panel is a scatter plot of two columns.
On the diagonal, each panel is the histogram of one column.
sns.pairplot uses every number column of the table.
sns.pairplot(iris)
plt.show()
Four columns give 16 panels.
Each scatter plot appears twice, once above and once below the diagonal, with the two axes swapped.
The panel of petal_length and petal_width shows that flowers with long petals also have wide petals.
In most panels the points form two groups.
The plot does not show which species a point belongs to.
Pair plot with color¶
Color adds one more column to every panel.
hue="species" gives each species its own color and adds a legend.
With hue, seaborn draws smooth density curves on the diagonal by default; diag_kind="hist" keeps the histograms.
sns.pairplot(iris, hue="species", diag_kind="hist")
plt.show()
Setosa is separate from the other two species in every panel. Versicolor and virginica are next to each other, and they overlap. The two groups of the first pair plot are setosa on one side and the other two species on the other side.
Dimension reduction with PCA¶
A pair plot needs 16 panels for four columns, and it needs 100 panels for ten columns. A dimension reduction method turns many columns into two, so that one scatter plot shows all of them. Principal component analysis (PCA) is a common method of this kind. It finds new axes, called principal components. The first component is the direction along which the data points differ the most. The second component is the direction with the most remaining variance, at a right angle to the first.
StandardScaler first gives each column a mean of 0 and a standard deviation of 1.
Without this step, a column with large values dominates the result.
explained_variance_ratio_ is the share of the variance that each component holds.
features = iris.drop(columns="species")
scaled = StandardScaler().fit_transform(features)
pca = PCA(n_components=2)
components = pca.fit_transform(scaled)
pca.explained_variance_ratio_
The result is array([0.72962445, 0.22850762]).
The first component holds 73% of the variance of the four standardized columns, and the second holds 23%.
Together they hold 96%, so a scatter plot of the two components keeps most of the differences between the flowers.
components has 150 rows and 2 columns: the position of each flower on the two components.
The next cell plots them, with one color for each species.
ratio = pca.explained_variance_ratio_
fig, ax = plt.subplots(layout="constrained")
for species in ["setosa", "versicolor", "virginica"]:
mask = (iris["species"] == species).to_numpy()
ax.scatter(components[mask, 0], components[mask, 1], label=species)
ax.set_xlabel(f"PC1 ({ratio[0]:.0%} of the variance)")
ax.set_ylabel(f"PC2 ({ratio[1]:.0%} of the variance)")
ax.legend(title="species", frameon=False, loc="center left", bbox_to_anchor=(1.0, 0.5))
ax.spines[["top", "right"]].set_visible(False)
plt.show()
Each point is one flower. Setosa is far from the other two species along the first component. Versicolor and virginica are next to each other and overlap a little. One scatter plot now shows the main pattern of the 16 panels of the pair plot.
layout="constrained" makes room for the legend, which is outside the plot.
A principal component is a mix of the four measurements, so its axis has no unit. The axis label gives the share of the variance instead.
PCA is also useful for data with many more columns. An example is the embeddings of posts, which have hundreds of columns.