Skip to content

Multivariate and time series

Principal components and clustering (via scikit-learn), and the series, its autocorrelation and a seasonal decomposition (via statsmodels), all redrawn in the depictr theme.

import numpy as np
import pandas as pd

import depictr as dp

wb = dp.wellbeing_survey()

PCA biplot

A PCA biplot, coloured by group, with the variable loadings.

p = dp.pca_plot(wb, group="region")
print(show(p, width=8, height=6))
depictr plot

Clustering

k-means clusters of the standardised data, drawn on the first two principal components. They are the clusters the silhouette plot below measures.

p = dp.cluster_plot(wb, k=3)
print(show(p))
depictr plot

Scree plot

The variance each principal component explains, with the running cumulative line.

p = dp.scree_plot(wb)
print(show(p))
depictr plot

Dendrogram

A hierarchical-clustering tree over the regional profiles.

p = dp.dendrogram_plot(wb.groupby("region", observed=True).mean(numeric_only=True))
print(show(p))
depictr plot

Silhouette

Each observation's silhouette width, grouped and ordered by cluster. Wide positive bars are well-placed observations, and a negative bar may belong to a neighbouring cluster.

p = dp.silhouette_plot(wb, k=3)
print(show(p))
depictr plot

Seasonal decomposition

A monthly series with a trend, a 12-period season and noise, and its decomposition into observed, trend, seasonal and residual components.

rng = np.random.default_rng(0)
t = np.arange(120)
series = pd.Series(
    50 + 0.3 * t + 10 * np.sin(2 * np.pi * t / 12) + rng.normal(0, 3, 120),
    index=pd.period_range("2016-01", periods=120, freq="M"),
)

p = dp.decompose_plot(series, period=12)
print(show(p, width=8, height=8))
depictr plot

The series with a rolling mean

The same series as a line, with a centred twelve-month moving average over it. Twelve is an even window, so the average is the 2ร—12 one, a twelve-month average followed by a two-month one, which centres it on each month.

p = dp.timeseries_plot(series, rolling=12)
print(show(p))
depictr plot

Autocorrelation

The autocorrelation function, with an approximate 95% band. The trend keeps the correlations high at short lags, and the season rides on their slow decay as a wave. It dips near lag six, where the series is half a cycle out of step with itself. It peaks again at lag twelve, the only multiple of the period within the default range of lags.

p = dp.acf_plot(series)
print(show(p))
depictr plot

The partial autocorrelation function, which leaves out what the shorter lags already explain. Lag one carries most of the dependence, and the value at lag twelve lies well inside the band.

p = dp.acf_plot(series, kind="pacf")
print(show(p))
depictr plot

The seasonal pattern

One line per year across the months, so the repeating shape and any drift between years are easy to read.

p = dp.seasonal_plot(series, period=12)
print(show(p))
depictr plot