Skip to main content

Dimensionality Reduction

What is dimensionality reduction?​

Dimensionality reduction is the process of describing data that has many variables per item with far fewer, while keeping the structure that matters. It turns, say, 64 pixel values per image into two or three coordinates that can be plotted or fed to a model. The best-known techniques are PCA (linear), and t-SNE and UMAP (non-linear).

A t-SNE map of 800 simulated handwritten digit images in a dark navy theme: ten coloured clusters, one per digit from 0 to 9, spread across a scatter chart, with a PCA scree plot beside it showing the share of variance explained by each of the first 20 principal components and a rising cumulative line, and small images of the first three principal components

A t-SNE map of 800 simulated 8 × 8 digit images, with the PCA scree plot and the first three components as images (sample data). Try the interactive version.

Key takeaways
  • High-dimensional data is hard to see and hard to model: distances lose contrast and the data needed grows quickly with each variable.
  • PCA rotates the data onto its directions of greatest variance. It is fast, repeatable and interpretable, but linear.
  • t-SNE and UMAP keep neighbours together and show clusters well, but cluster sizes and the gaps between clusters are not to scale.
  • A scree plot shows how much of the data a PCA picture leaves out; an embedding plot needs several settings before you trust a pattern.

Why reduce dimensions? The curse of dimensionality​

A dimension here is one variable measured for every item: one pixel of an image, one gene's expression level, one sensor channel. A dataset with 64 variables is a cloud of points in a 64-dimensional space. You can't draw it, and many methods that work well in two or three dimensions behave badly in it. Richard Bellman called this the curse of dimensionality.

Two effects explain most of it:

  • Space empties out. To keep the same density of samples, the number you need grows exponentially with the number of dimensions. Take the share of a unit cube that lies more than 0.05 from every face: it is 81% in 2 dimensions, 35% in 10 and 0.003% in 100. Almost every point ends up near an edge.
  • Distances stop discriminating. We scattered 1,000 random points in a unit cube and compared each query point's nearest and farthest neighbour. In 2 dimensions the nearest was on average 2% as far away as the farthest; in 10 dimensions, 27%; in 100, 70%; in 1,000, 89%. When everything is about equally far away, "nearest neighbour" means little. Beyer and colleagues proved this concentration happens for a broad class of data distributions.

Real data is rarely uniform. Pixels next to each other are correlated, and genes act in pathways, so the points usually lie near a much smaller surface inside the big space, often called a manifold. Dimensionality reduction tries to find that surface and describe each point by its position on it. That helps in four ways: you can plot the data, models train faster and overfit less, noise in the dropped directions is removed, and storage shrinks.

Dimensionality reduction techniques​

The techniques fall into two families. Feature selection keeps a subset of the original variables and drops the rest, for example removing near-constant or highly correlated columns. Feature extraction builds new variables from combinations of all the old ones. PCA, t-SNE and UMAP are feature extraction methods.

TechniqueLinear?Supervised?What it keepsTypical use
PCA (principal component analysis)LinearNoDirections of greatest variancePreprocessing, compression, first look at any numeric dataset
LDA (linear discriminant analysis)LinearYes, uses class labelsDirections that best separate known classesFeatures for a classifier
ICA (independent component analysis)LinearNoStatistically independent sourcesSeparating mixed signals, such as EEG artefacts
NMF (non-negative matrix factorisation)LinearNoAdditive, non-negative partsTopics in text, spectra, images
Kernel PCANon-linearNoVariance after a kernel mappingCurved structure that PCA misses
MDS and IsomapNon-linear (Isomap)NoPairwise or along-the-surface distancesMaps from distance tables
t-SNENon-linearNoLocal neighbourhoods2D or 3D maps of clusters
UMAPNon-linearNo (optional labels)Local neighbourhoods, with a little more global layout2D or 3D maps of large datasets; general reduction
AutoencoderNon-linearNoWhatever a neural network needs to rebuild the inputImages, audio, very large datasets

The rest of this page covers the three most used for visualisation: PCA, t-SNE and UMAP.

How PCA works​

Principal component analysis (PCA) finds new axes, called principal components, that are combinations of the original variables. The first points along the direction in which the data varies most; the second along the direction of greatest remaining variance, at right angles to the first; and so on. Karl Pearson described it in 1901 as fitting the line or plane closest to a set of points, and Harold Hotelling developed it in 1933.

The steps:

  1. Centre the data: subtract each variable's mean. If the variables are in different units, also divide by each one's standard deviation (standardise), or the variable with the biggest numbers dominates.
  2. Compute the covariance matrix, C=1n−1XTXC = \frac{1}{n-1} X^{\mathsf T} X, for the centred data XX with nn rows.
  3. Find the eigenvectors and eigenvalues of CC. Each eigenvector is a principal component; its eigenvalue is the variance of the data along it.
  4. Sort the components by eigenvalue, keep the first kk, and project each row onto them. The projections are the scores: the coordinates you plot.

In practice, libraries usually compute the same result with a singular value decomposition of XX, which is more accurate numerically.

A worked PCA example in two dimensions​

Take five points: (1, 2), (2, 1), (3, 4), (4, 3) and (5, 5). Both variables have a mean of 3, a variance of 2.5 and a covariance with each other of 2.0:

C=(2.52.02.02.5)C = \begin{pmatrix} 2.5 & 2.0 \\ 2.0 & 2.5 \end{pmatrix}

Solving det⁡(C−λI)=(2.5−λ)2−4=0\det(C - \lambda I) = (2.5 - \lambda)^2 - 4 = 0 gives eigenvalues 4.5 and 0.5. The first component is the diagonal (0.71, 0.71) and the second is (0.71, −0.71). The total variance is 5, so PC1 explains 4.5 / 5 = 90% and PC2 the other 10%.

Left: five points on a grid with their mean at (3, 3), a long orange arrow along the diagonal for the first principal component and a short purple arrow across it for the second, with dashed lines projecting each point onto the first component. Right: the five PC1 scores on a number line at minus 2.12 for two points, 0.71 for two points and 2.83 for one, with a box giving the covariance matrix and the 90% and 10% shares of variance

Projecting onto PC1 gives each point one number: −2.12, −2.12, 0.71, 0.71 and 2.83. The two-dimensional data is now one-dimensional and keeps 90% of its variance. Points (1, 2) and (2, 1) now have the same score, because the difference between them lay along PC2, which was dropped.

How to read a PCA plot​

A PCA analysis usually comes with three charts.

  • The scree plot is a bar chart of each component's share of the variance, the explained variance ratio, in order. Raymond Cattell suggested keeping the components before the "elbow", where the bars level off into rubble, like scree at the foot of a cliff. A cumulative line on the same chart shows how much the first kk components keep together.
  • The score plot is a scatter plot of PC1 against PC2 (or a 3D plot with PC3). Points close together have similar values across the variables PCA kept. Clusters, outliers and gradients show up here.
  • The loadings are the weights of each original variable in a component. A large positive or negative loading means the variable drives that component. A biplot draws the scores as points and the loadings as arrows on the same axes, so you can see which variables push points in which direction.

Read the axis titles first. "PC1 (12%)" means the horizontal axis carries only 12% of the variance, so a picture that looks clean may leave most of the data out. In the live demo, the first two components of the 64-pixel digit images explain 21.7%, the first three 30.2%, and 26 are needed to reach 90%. The demo also shows the first three loadings as 8 × 8 images, so you can see which strokes each component responds to.

How t-SNE works​

t-SNE (t-distributed stochastic neighbour embedding) is a non-linear method designed for drawing high-dimensional data in two or three dimensions. Laurens van der Maaten and Geoffrey Hinton published it in 2008. Instead of keeping variance, it keeps neighbourhoods: which points are close to which.

  1. For each point, t-SNE turns distances to every other point into probabilities with a Gaussian centred on it: close points get a high probability of being "picked as a neighbour", far ones almost none. The width of each Gaussian is set separately for each point, so that dense and sparse regions get the same effective number of neighbours.
  2. It does the same on the map, but with a Student t-distribution (one degree of freedom) in place of the Gaussian. Its tails are much heavier. Moderately distant points can then sit far apart on the map without much penalty, which avoids crushing everything into the middle (the "crowding problem").
  3. It moves the map points by gradient descent to make the two sets of probabilities match, minimising the Kullback-Leibler divergence between them.

Common implementations exaggerate the input probabilities for the first 250 or so iterations, which pulls clusters together early on, then let the map relax. The demo on this page does the same, and its readout shows the KL divergence falling as the map settles.

Perplexity: the main t-SNE setting​

Perplexity sets how many neighbours each point effectively considers. Each point's Gaussian is widened or narrowed until its perplexity, 2H2^{H} where HH is the entropy of its neighbour probabilities in bits, equals the target. The original paper suggests values between 5 and 50.

  • Low perplexity looks only at the closest few points. Real clusters can break into small islands, and random noise can look clumpy.
  • High perplexity blends in more distant points. Clusters merge more easily, but more of the overall arrangement survives.
  • Perplexity must be smaller than the number of points. With a few hundred points, values near the top of the range behave like a global method.

In the demo's digits, a perplexity of 2 keeps 50% of each point's 10 nearest neighbours, 5 keeps 57%, 30 keeps 63% and 100 keeps 61%. The best value depends on the data, so try several before reading meaning into a shape.

What t-SNE distances do and don't mean​

Left: three groups in the original data: a tight small blue group, a widely spread orange group, and a green group far from both. Right: the same groups on a t-SNE map, where they come out about the same size and roughly evenly spaced. Numbered callouts: 1, points that were neighbours stay neighbours; 2, groups come out a similar size; 3, gaps between groups are not to scale; 4, the axes have no units or meaning

t-SNE's cost function penalises near neighbours that end up far apart much more than distant points that end up close, and the per-point Gaussian widths even out density. As a result:

  • Points that were neighbours in the data usually stay neighbours on the map. The reverse is less certain: the cost barely penalises distant points placed close together, so two points next to each other on the map are not always close in the data.
  • Cluster sizes on the map say little about how spread out the clusters really are.
  • Gaps between clusters are not to scale; a big gap doesn't mean "more different".
  • The axes have no units and no meaning; the map can be rotated or mirrored freely.
  • Each run, and each starting layout, can arrange the clusters differently.

Wattenberg, Viégas and Johnson illustrate each of these with interactive examples in "How to Use t-SNE Effectively" (Distill, 2016).

How UMAP works​

UMAP (uniform manifold approximation and projection), introduced by Leland McInnes, John Healy and James Melville in 2018, works in two stages. It first builds a weighted graph linking each point to its nearest neighbours, scaling each point's distances by how far away its own nearest neighbour is. It then lays out a graph in two or three dimensions whose edges match as closely as possible, pulling linked points together and pushing a sample of the others apart.

Two settings matter most:

  • n_neighbors (15 by default in the reference implementation) plays the role of perplexity. Small values show fine local detail; large values show more of the broad structure.
  • min_dist (0.1 by default) sets how tightly points may pack on the map. Small values give dense, well-separated clumps; larger values spread points out evenly, which helps when you care about overall shape.

UMAP is usually faster than t-SNE on large datasets, scales to millions of points, can place new points on an existing map and can reduce to more than three dimensions for use as model input. Its maps need the same care in reading as t-SNE's. Kobak and Linderman showed that much of the extra global structure UMAP was credited with comes from its starting layout, and that t-SNE started from a PCA layout keeps global structure about as well.

This page's live demo computes PCA and t-SNE in the browser. UMAP's graph construction and sampling make it a much longer example, so it is described here rather than demonstrated.

PCA vs t-SNE vs UMAP​

PCAt-SNEUMAP
TypeLinearNon-linearNon-linear
PreservesGlobal variance and large distancesLocal neighbourhoodsLocal neighbourhoods, some global layout
Same result every runYes (up to the sign of each axis)No, unless the start and random seed are fixedNo, unless the random seed is fixed
SpeedFast: one eigendecomposition or SVDSlow: exact version grows with the square of the points; Barnes-Hut approximation scales to large datasetsUsually faster than t-SNE, scales to millions of points
New pointsProject with the same componentsNot built in to most implementations; some libraries can add points to an existing mapSupported
Axes meanWeighted sums of the original variablesNothingNothing
Main settingsNumber of components; whether to standardisePerplexity, iterations, learning raten_neighbors, min_dist
Best forPreprocessing, compression, interpretable axes, a first lookRevealing clusters in small to medium datasetsClusters in large datasets; reduction before clustering

A common workflow combines them: standardise the data, run PCA to keep around 50 components and drop noise, then run t-SNE or UMAP on those components for the picture.

How to read an embedding plot​

An embedding plot is the scatter chart of the reduced coordinates, usually coloured by a known label or by a variable of interest. A checklist for reading one:

  1. Check what was reduced and how: which variables, whether they were standardised, which method and settings.
  2. Look at the colours before the shapes. If points of the same label sit together, the variables carry that label's signal. Mixed colours inside one cluster can be mislabelled items or a real overlap.
  3. For questions of size and distance, switch to the PCA plot, whose axes keep their scale along the components shown.
  4. Look for small islands and long thin strands. Islands can be a real subgroup or an artefact of low perplexity; strands often trace a continuous change, such as slant in handwriting or time in a process.
  5. Inspect individual points: outliers, and points of one colour inside another colour's group. Look at the original item behind each one; in the demo, hovering a point shows its digit image.

Where dimensionality reduction is used​

Dimensionality reduction is used wherever each item has too many measurements to plot or model directly, from cells and images to sensor batches and yield curves.

  • Biology and medicine. Single-cell genomics routinely shows each cell as a point on a t-SNE or UMAP map, coloured by cell type. Flow cytometry and mass spectrometry use the same maps, and PCA is a standard first look at gene expression and population genetics data. See how SciChart is used in diagnostics and life sciences software.
  • Machine learning. Embeddings from language and image models have hundreds of dimensions; teams plot them in 2D or 3D to check that similar items land together, and use PCA to compress features before training.
  • Industrial process monitoring. PCA models of normal operation flag a batch or a wafer whose sensor readings fall outside the usual pattern.
  • Finance. PCA of interest-rate curves typically finds a few components that work like level, slope and curvature, used to describe and hedge the risk.
  • Images and signals. PCA on faces ("eigenfaces"), compression, and denoising by dropping the smallest components.

Common dimensionality reduction mistakes​

Most mistakes come from unscaled inputs, from trusting a single run, or from reading a non-linear map as if its distances were measurements.

  • Running PCA on unscaled variables. A variable measured in grams beside one in kilograms dominates PC1 only because of its units. Standardise when the variables are in different units.
  • Calling a 2D PCA plot "the data". In the demo, the first two components keep only 13% of each point's 10 nearest neighbours, against 63% for t-SNE. Put the explained variance in the axis titles.
  • Comparing two maps by position. Each t-SNE or UMAP run can put a cluster anywhere. To compare two datasets, embed them together in one run and colour by dataset.
  • Trusting one t-SNE run. Change the perplexity and the start. In the demo, two random starts put the clusters in different places but keep a similar share of neighbours (63% and 61%), while the arrangement from a PCA start is the same every time.
  • Stopping t-SNE too early. During early exaggeration the map is compressed and misleading. Let it run until the KL divergence stops falling.
  • Clustering the map instead of the data. Clusters drawn around t-SNE islands inherit its distortions. Cluster in the original space or on PCA components, then colour the map by the result.
  • Fitting the reduction on the test set. For a model, fit PCA (means, scaling and components) on the training data only, then apply it to the test data, or the evaluation leaks information.
  • Using t-SNE output as model features. Most t-SNE implementations have no transform for new points, and its coordinates change from run to run. Use PCA, UMAP or an autoencoder for features.

How to plot PCA and t-SNE results in JavaScript, React or Angular​

The demo computes PCA and an exact t-SNE for 800 simulated 8 × 8 digit images (64 dimensions each) in the browser. It runs four t-SNE iterations per animation frame, up to 1,000, and redraws the 2D scatter chart or 3D point cloud after each step so you can watch the map form.

Choose the Method (t-SNE or PCA) and the View: a 2D scatter chart or a 3D point cloud, which reduces to three dimensions. For t-SNE, set the Perplexity (applied when you release the slider), choose whether to Start from a PCA layout or a random one, and use Pause and Restart t-SNE to watch the map form. Each restart from a random layout uses a new seed. The readout shows the iteration, the KL divergence and the share of each point's 10 nearest neighbours kept by the map. The side panel shows the PCA scree plot, the first three principal components as images, and the digit under the mouse. The mouse wheel zooms, dragging pans the 2D chart or rotates the 3D one, and a double-click resets the view.

Here is the code for this chart. The PCA, t-SNE and neighbourhood maths are plain JavaScript with no machine learning library; SciChart.js draws the map as a scatter series or a 3D point cloud and the scree plot as columns and a line.

// PCA and t-SNE of 800 simulated 8 × 8 digit images (64 dimensions each), computed in the browser and drawn with
// SciChart.js as a 2D scatter chart or a 3D point cloud, with a PCA scree plot alongside.
const {
SciChartSurface,
SciChart3DSurface,
NumericAxis,
NumericAxis3D,
NumberRange,
EAutoRange,
EAxisAlignment,
Vector3,
XyDataSeries,
XyzDataSeries3D,
XyScatterRenderableSeries,
ScatterRenderableSeries3D,
FastColumnRenderableSeries,
FastLineRenderableSeries,
EllipsePointMarker,
SpherePointMarker3D,
EStrokePaletteMode,
parseColorToUIntArgb,
WaveAnimation,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
OrbitModifier3D,
MouseWheelZoomModifier3D,
ResetCamera3DModifier,
TooltipModifier3D,
XyzSeriesInfo3D
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// --- PCA (plain JavaScript) ---

// Eigenvalues and eigenvectors of a symmetric d × d matrix (row-major array) by cyclic Jacobi rotations.
// Returns them sorted from the largest eigenvalue down; vectors[k] is the unit eigenvector for values[k].
function symmetricEigen(matrix, d) {
const a = Float64Array.from(matrix);
const v = new Float64Array(d * d);
for (let i = 0; i < d; i++) v[i * d + i] = 1;
for (let sweep = 0; sweep < 100; sweep++) {
let off = 0;
for (let p = 0; p < d; p++) for (let q = p + 1; q < d; q++) off += a[p * d + q] * a[p * d + q];
if (off < 1e-22) break;
for (let p = 0; p < d; p++) {
for (let q = p + 1; q < d; q++) {
const apq = a[p * d + q];
if (Math.abs(apq) < 1e-300) continue;
// Rotate rows and columns p and q by the angle that zeroes a[p][q]
const theta = (a[q * d + q] - a[p * d + p]) / (2 * apq);
const t = Math.sign(theta || 1) / (Math.abs(theta) + Math.sqrt(theta * theta + 1));
const c = 1 / Math.sqrt(t * t + 1);
const s = t * c;
for (let k = 0; k < d; k++) {
const akp = a[k * d + p], akq = a[k * d + q];
a[k * d + p] = c * akp - s * akq;
a[k * d + q] = s * akp + c * akq;
}
for (let k = 0; k < d; k++) {
const apk = a[p * d + k], aqk = a[q * d + k];
a[p * d + k] = c * apk - s * aqk;
a[q * d + k] = s * apk + c * aqk;
}
for (let k = 0; k < d; k++) {
const vkp = v[k * d + p], vkq = v[k * d + q];
v[k * d + p] = c * vkp - s * vkq;
v[k * d + q] = s * vkp + c * vkq;
}
}
}
}
const order = Array.from({ length: d }, (_, i) => i).sort((i, j) => a[j * d + j] - a[i * d + i]);
const values = order.map((i) => Math.max(0, a[i * d + i]));
const vectors = order.map((i) => {
const vector = Array.from({ length: d }, (_, k) => v[k * d + i]);
// An eigenvector's sign is arbitrary: make its largest entry positive so the plot doesn't flip between runs
const big = vector.reduce((best, x) => (Math.abs(x) > Math.abs(best) ? x : best), 0);
return big < 0 ? vector.map((x) => -x) : vector;
});
return { values, vectors };
}

// PCA of n rows × d columns: centre each column, take the covariance matrix's eigenvectors (the principal
// components, or loadings) and project every row onto them (the scores)
function pca(X, n, d) {
const mean = new Float64Array(d);
for (let i = 0; i < n; i++) for (let j = 0; j < d; j++) mean[j] += X[i * d + j] / n;
const centred = X.map((x, k) => x - mean[k % d]);
const covariance = new Float64Array(d * d);
for (let i = 0; i < n; i++) {
for (let j = 0; j < d; j++) {
const xj = centred[i * d + j];
if (xj === 0) continue;
for (let k = j; k < d; k++) covariance[j * d + k] += (xj * centred[i * d + k]) / (n - 1);
}
}
for (let j = 0; j < d; j++) for (let k = 0; k < j; k++) covariance[j * d + k] = covariance[k * d + j];
const { values, vectors } = symmetricEigen(covariance, d);
const total = values.reduce((sum, x) => sum + x, 0);
const score = (i, component) => {
let s = 0;
for (let j = 0; j < d; j++) s += centred[i * d + j] * vectors[component][j];
return s;
};
return { values, vectors, explained: values.map((x) => x / total), score };
}

// --- t-SNE (plain JavaScript, exact gradient: fine for up to a few thousand points) ---

// Squared Euclidean distances between all pairs of rows
function squaredDistances(X, n, d) {
const D = new Float64Array(n * n);
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
let s = 0;
for (let k = 0; k < d; k++) {
const diff = X[i * d + k] - X[j * d + k];
s += diff * diff;
}
D[i * n + j] = D[j * n + i] = s;
}
}
return D;
}

// Input similarities P. For each point i, a binary search finds the Gaussian width whose neighbour
// probabilities p(j|i) have perplexity 2^H = the target (H = entropy in bits); then P is symmetrised.
function affinities(D, n, perplexity) {
const P = new Float64Array(n * n);
const targetEntropy = Math.log(perplexity); // natural log: perplexity = e^H here, the same as 2^H in bits
const row = new Float64Array(n);
for (let i = 0; i < n; i++) {
let beta = 1; // beta = 1 / (2 sigma²)
let lo = 0;
let hi = Infinity;
let minD = Infinity;
for (let j = 0; j < n; j++) if (j !== i && D[i * n + j] < minD) minD = D[i * n + j];
for (let attempt = 0; attempt < 64; attempt++) {
let sum = 0;
let weighted = 0;
for (let j = 0; j < n; j++) {
// subtract the nearest distance before exp() so small widths don't underflow to zero
row[j] = j === i ? 0 : Math.exp(-beta * (D[i * n + j] - minD));
sum += row[j];
weighted += row[j] * (D[i * n + j] - minD);
}
const entropy = Math.log(sum) + (beta * weighted) / sum;
if (Math.abs(entropy - targetEntropy) < 1e-6) break;
if (entropy > targetEntropy) {
lo = beta;
beta = hi === Infinity ? beta * 2 : (beta + hi) / 2;
} else {
hi = beta;
beta = (beta + lo) / 2;
}
}
let sum = 0;
for (let j = 0; j < n; j++) sum += row[j];
for (let j = 0; j < n; j++) P[i * n + j] = row[j] / sum;
}
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
const p = Math.max((P[i * n + j] + P[j * n + i]) / (2 * n), 1e-12);
P[i * n + j] = P[j * n + i] = p;
}
P[i * n + i] = 0;
}
return P;
}

// Gradient descent on the Kullback-Leibler divergence between P and the Student-t similarities Q of the map,
// with momentum, per-coordinate gains and early exaggeration, as in van der Maaten and Hinton (2008)
function createTsne(P, n, dims, initial) {
const Y = Float64Array.from(initial);
const velocity = new Float64Array(n * dims);
const gains = new Float64Array(n * dims).fill(1);
const grad = new Float64Array(n * dims);
const num = new Float64Array(n * n);
const learningRate = 200;
let iteration = 0;
let kl = NaN;
function step() {
const exaggeration = iteration < 250 ? 12 : 1;
const momentum = iteration < 250 ? 0.5 : 0.8;
let Z = 0;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
let s = 0;
for (let k = 0; k < dims; k++) {
const diff = Y[i * dims + k] - Y[j * dims + k];
s += diff * diff;
}
const q = 1 / (1 + s); // Student-t kernel with one degree of freedom
num[i * n + j] = num[j * n + i] = q;
Z += 2 * q;
}
}
grad.fill(0);
const measure = iteration % 10 === 0; // the KL divergence is only for the readout: work it out every 10 steps
let divergence = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (i === j) continue;
const p = P[i * n + j];
const q = num[i * n + j];
const force = 4 * (exaggeration * p - q / Z) * q;
for (let k = 0; k < dims; k++) grad[i * dims + k] += force * (Y[i * dims + k] - Y[j * dims + k]);
if (measure) divergence += p * Math.log(p / Math.max(q / Z, 1e-12));
}
}
for (let k = 0; k < n * dims; k++) {
gains[k] = Math.sign(grad[k]) !== Math.sign(velocity[k]) ? gains[k] + 0.2 : Math.max(0.01, gains[k] * 0.8);
velocity[k] = momentum * velocity[k] - learningRate * gains[k] * grad[k];
Y[k] += velocity[k];
}
for (let k = 0; k < dims; k++) {
let mean = 0;
for (let i = 0; i < n; i++) mean += Y[i * dims + k] / n;
for (let i = 0; i < n; i++) Y[i * dims + k] -= mean;
}
if (measure) kl = divergence;
iteration++;
}
return { Y, step, get iteration() { return iteration; }, get kl() { return kl; } };
}

// Share of each point's k nearest neighbours in the original space that are also among its k nearest in the map:
// 1 means every local neighbourhood survived the reduction
function nearestNeighbours(D, n, k) {
const result = [];
for (let i = 0; i < n; i++) {
const order = Array.from({ length: n }, (_, j) => j).filter((j) => j !== i);
order.sort((a, b) => D[i * n + a] - D[i * n + b]);
result.push(order.slice(0, k));
}
return result;
}
function neighbourhoodKept(highNeighbours, Y, n, dims, k) {
const mapNeighbours = nearestNeighbours(squaredDistances(Y, n, dims), n, k);
let kept = 0;
for (let i = 0; i < n; i++) {
const set = new Set(mapNeighbours[i]);
for (const j of highNeighbours[i]) if (set.has(j)) kept++;
}
return kept / (n * k);
}

// --- Run the maths once for the data ---
const { pixels, labels, n, dims: d } = data;
const pcaResult = pca(pixels, n, d);
const highD = squaredDistances(pixels, n, d);
const K = 10;
const highNeighbours = nearestNeighbours(highD, n, K);
const pcaCoords = (dims) => {
const Y = new Float64Array(n * dims);
for (let i = 0; i < n; i++) for (let k = 0; k < dims; k++) Y[i * dims + k] = pcaResult.score(i, k);
return Y;
};

// --- The charts ---
const theme = new SciChartJsNavyTheme();
const COLOURS = ["#50C7E0", "#F48420", "#3BD16F", "#E36FD4", "#F6E05E", "#EF5350", "#AE418D", "#B6E35B", "#9B8AFB", "#FFFFFF"];
const argb = COLOURS.map((c) => parseColorToUIntArgb(c));
ui.key.innerHTML = COLOURS.map(
(c, digit) =>
`<span style="display:inline-flex; align-items:center; gap:4px"><span style="width:11px; height:11px; ` +
`border-radius:50%; background:${c}"></span>${digit}</span>`
).join("");

// 2D: one scatter series; a palette provider colours each point by its digit
const chart2d = await SciChartSurface.create(ui.chart2d, { theme });
const xAxis = new NumericAxis(chart2d.wasmContext, { axisTitle: "Dimension 1", autoRange: EAutoRange.Always, growBy: new NumberRange(0.05, 0.05), labelPrecision: 0 });
const yAxis = new NumericAxis(chart2d.wasmContext, { axisTitle: "Dimension 2", axisAlignment: EAxisAlignment.Left, autoRange: EAutoRange.Always, growBy: new NumberRange(0.05, 0.05), labelPrecision: 0 });
chart2d.sciChartSurface.xAxes.add(xAxis);
chart2d.sciChartSurface.yAxes.add(yAxis);
const scatterData = new XyDataSeries(chart2d.wasmContext, { dataSeriesName: "Digits", dataIsSortedInX: false });
const byDigit = {
strokePaletteMode: EStrokePaletteMode.SOLID,
onAttached: () => {},
onDetached: () => {},
overridePointMarkerArgb: (x, y, index) => ({ fill: argb[labels[index]], stroke: argb[labels[index]] })
};
chart2d.sciChartSurface.renderableSeries.add(
new XyScatterRenderableSeries(chart2d.wasmContext, {
dataSeries: scatterData,
pointMarker: new EllipsePointMarker(chart2d.wasmContext, { width: 7, height: 7, strokeThickness: 0, fill: "#FFFFFF", opacity: 0.85 }),
paletteProvider: byDigit
})
);
chart2d.sciChartSurface.chartModifiers.add(
new CursorModifier({
showTooltip: true,
showAxisLabels: false,
tooltipDataTemplate: (infos) => {
const info = infos.find((s) => s.isHit);
if (!info) return [];
drawDigit(ui.hoverCanvas, info.dataSeriesIndex);
return [`Digit ${labels[info.dataSeriesIndex]} (sample ${info.dataSeriesIndex})`];
}
}),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);

// 3D: one point cloud, coloured per point through its metadata. Created the first time the 3D view is chosen.
async function create3d() {
const { sciChart3DSurface, wasmContext } = await SciChart3DSurface.create(ui.chart3d, {
theme,
worldDimensions: new Vector3(200, 200, 200),
cameraOptions: { position: new Vector3(-260, 200, -260), target: new Vector3(0, 0, 0) }
});
sciChart3DSurface.xAxis = new NumericAxis3D(wasmContext, { axisTitle: "Dimension 1", labelPrecision: 0 });
sciChart3DSurface.yAxis = new NumericAxis3D(wasmContext, { axisTitle: "Dimension 2", labelPrecision: 0 });
sciChart3DSurface.zAxis = new NumericAxis3D(wasmContext, { axisTitle: "Dimension 3", labelPrecision: 0 });
const dataSeries = new XyzDataSeries3D(wasmContext, { dataSeriesName: "Digits" });
sciChart3DSurface.renderableSeries.add(
new ScatterRenderableSeries3D(wasmContext, {
dataSeries,
pointMarker: new SpherePointMarker3D(wasmContext, { size: 6, fill: "#FFFFFF" })
})
);
sciChart3DSurface.chartModifiers.add(
new OrbitModifier3D(), // drag to rotate
new MouseWheelZoomModifier3D(), // scroll to zoom
new ResetCamera3DModifier(), // double-click to reset the view
new TooltipModifier3D({
tooltipDataTemplate: (info) => {
if (!(info instanceof XyzSeriesInfo3D) || !info.isHit) return [];
drawDigit(ui.hoverCanvas, info.dataSeriesIndex);
return [`Digit ${labels[info.dataSeriesIndex]} (sample ${info.dataSeriesIndex})`];
}
})
);
return { sciChart3DSurface, dataSeries };
}

// Scree plot: the share of variance explained by each of the first 20 principal components, and the running total
const scree = await SciChartSurface.create(ui.scree, { theme, title: "PCA scree plot", titleStyle: { fontSize: 14 } });
const small = { axisTitleStyle: { fontSize: 13 }, labelStyle: { fontSize: 11 }, labelPrecision: 0 };
scree.sciChartSurface.xAxes.add(new NumericAxis(scree.wasmContext, { ...small, axisTitle: "Component", growBy: new NumberRange(0.04, 0.04) }));
// Left axis: each component's share; right axis: the running total, 0 to 100%
scree.sciChartSurface.yAxes.add(
new NumericAxis(scree.wasmContext, { ...small, axisTitle: "Each (%)", axisAlignment: EAxisAlignment.Left, autoRange: EAutoRange.Always, growBy: new NumberRange(0, 0.1) }),
new NumericAxis(scree.wasmContext, { ...small, id: "cumulative", axisTitle: "Cumulative (%)", axisAlignment: EAxisAlignment.Right, visibleRange: new NumberRange(0, 100) })
);
const components = Array.from({ length: 20 }, (_, k) => k + 1);
const individual = components.map((k) => 100 * pcaResult.explained[k - 1]);
let running = 0;
const cumulative = individual.map((x) => (running += x));
scree.sciChartSurface.renderableSeries.add(
new FastColumnRenderableSeries(scree.wasmContext, {
dataSeries: new XyDataSeries(scree.wasmContext, { xValues: components, yValues: individual, dataSeriesName: "Each component" }),
fill: "#50C7E0CC",
stroke: "#50C7E0",
cornerRadius: 8,
dataPointWidth: 0.7,
animation: new WaveAnimation({ duration: 1000 })
}),
new FastLineRenderableSeries(scree.wasmContext, {
dataSeries: new XyDataSeries(scree.wasmContext, { xValues: components, yValues: cumulative, dataSeriesName: "Cumulative" }),
stroke: "#F48420",
strokeThickness: 2,
yAxisId: "cumulative"
})
);
scree.sciChartSurface.chartModifiers.add(new CursorModifier({ showTooltip: true, showAxisLabels: false }));

// Small images: the first three principal components as 8 × 8 pictures (blue negative, orange positive),
// and the digit under the mouse
function drawImage(canvas, values, colourOf) {
const context = canvas.getContext("2d");
const cell = canvas.width / SIDE;
values.forEach((value, k) => {
context.fillStyle = colourOf(value);
context.fillRect((k % SIDE) * cell, Math.floor(k / SIDE) * cell, cell, cell);
});
}
function drawDigit(canvas, index) {
const values = Array.from(pixels.subarray(index * d, (index + 1) * d));
drawImage(canvas, values, (v) => `rgb(${Math.round(16 * v)},${Math.round(16 * v)},${Math.round(16 * v)})`);
}
pcaResult.vectors.slice(0, 3).forEach((vector, k) => {
const max = Math.max(...vector.map(Math.abs));
drawImage(ui.loadingCanvases[k], vector, (w) => {
const t = Math.abs(w) / max;
return w < 0 ? `rgba(80,199,224,${t})` : `rgba(244,132,32,${t})`;
});
});
drawDigit(ui.hoverCanvas, 0);

// --- Drawing the current embedding ---
let view = 2;
let tsne = null;
let chart3dPromise = null;
let kept = NaN;
let restartCount = 0;
let paused = false;

async function show(Y, dims) {
if (dims === 2) {
const xs = new Float64Array(n), ys = new Float64Array(n);
for (let i = 0; i < n; i++) {
xs[i] = Y[2 * i];
ys[i] = Y[2 * i + 1];
}
scatterData.clear();
scatterData.appendRange(xs, ys);
} else {
chart3dPromise = chart3dPromise || create3d();
const running3d = await chart3dPromise;
const xs = new Float64Array(n), ys = new Float64Array(n), zs = new Float64Array(n);
const metadata = new Array(n);
let extent = 1e-9;
for (let i = 0; i < n; i++) {
xs[i] = Y[3 * i];
ys[i] = Y[3 * i + 1];
zs[i] = Y[3 * i + 2];
extent = Math.max(extent, Math.abs(xs[i]), Math.abs(ys[i]), Math.abs(zs[i]));
metadata[i] = { vertexColor: argb[labels[i]] };
}
running3d.dataSeries.clear();
running3d.dataSeries.appendRange(xs, ys, zs, metadata);
const range = new NumberRange(-extent * 1.05, extent * 1.05); // equal ranges keep the map's shape
const surface = running3d.sciChart3DSurface;
surface.xAxis.visibleRange = range;
surface.yAxis.visibleRange = range;
surface.zAxis.visibleRange = range;
}
}

function updateReadout() {
const method = ui.methodSelect.value;
const keptText = Number.isFinite(kept) ? ` · ${(100 * kept).toFixed(0)}% of 10 nearest neighbours kept` : "";
if (method === "pca") {
const shown = pcaResult.explained.slice(0, view).reduce((s, x) => s + x, 0);
ui.readout.textContent = `PCA: the first ${view} components explain ${(100 * shown).toFixed(1)}% of the variance${keptText}`;
} else if (tsne) {
const phase = tsne.iteration < 250 ? "early exaggeration" : tsne.iteration < 1000 ? "refining" : "done";
ui.readout.textContent = `t-SNE iteration ${tsne.iteration} of 1,000 (${phase}) · KL divergence ${Number.isFinite(tsne.kl) ? tsne.kl.toFixed(3) : "–"}${keptText}`;
}
}

// Start t-SNE again with the current perplexity, view and starting layout
let P = null;
let pPerplexity = 0;
function restartTsne() {
const perplexity = Number(ui.perplexityInput.value);
if (!P || pPerplexity !== perplexity) {
P = affinities(highD, n, perplexity);
pPerplexity = perplexity;
}
let initial;
if (ui.initSelect.value === "pca") {
// PCA start, scaled so the first coordinate has a standard deviation of 0.0001 (Kobak and Linderman, 2021)
initial = pcaCoords(view);
const sd = Math.sqrt(pcaResult.values[0]);
for (let k = 0; k < initial.length; k++) initial[k] *= 1e-4 / sd;
} else {
// Random start: a new seed on every restart, so the global layout changes from run to run
let seed = 1 + 7919 * ++restartCount;
const random = () => {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
};
initial = Float64Array.from({ length: n * view }, () => 1e-4 * Math.sqrt(-2 * Math.log(random() + 1e-12)) * Math.cos(2 * Math.PI * random()));
}
tsne = createTsne(P, n, view, initial);
kept = NaN;
paused = false;
ui.runButton.textContent = "Pause";
}

// Run a few t-SNE iterations per animation frame and redraw, until 1,000 iterations
let busy = false;
async function animate() {
if (!busy && ui.methodSelect.value === "tsne" && tsne && !paused && tsne.iteration < 1000) {
busy = true;
for (let s = 0; s < 4 && tsne.iteration < 1000; s++) tsne.step();
if (tsne.iteration % 100 === 0) kept = neighbourhoodKept(highNeighbours, tsne.Y, n, view, K);
await show(tsne.Y, view);
updateReadout();
busy = false;
}
if (!chart2d.sciChartSurface.isDeleted) requestAnimationFrame(animate);
}

async function onSettingsChanged() {
view = Number(ui.dimsSelect.value);
const method = ui.methodSelect.value;
ui.chart2d.style.display = view === 2 ? "" : "none";
ui.chart3d.style.display = view === 3 ? "" : "none";
ui.perplexityOutput.textContent = ui.perplexityInput.value;
for (const control of [ui.perplexityInput, ui.initSelect, ui.runButton, ui.restartButton]) control.disabled = method !== "tsne";
if (method === "pca") {
const Y = pcaCoords(view);
kept = neighbourhoodKept(highNeighbours, Y, n, view, K);
await show(Y, view);
} else {
restartTsne();
await show(tsne.Y, view);
}
if (view === 2) chart2d.sciChartSurface.zoomExtents();
updateReadout();
}

ui.methodSelect.addEventListener("change", onSettingsChanged);
ui.dimsSelect.addEventListener("change", onSettingsChanged);
ui.perplexityInput.addEventListener("input", () => (ui.perplexityOutput.textContent = ui.perplexityInput.value));
ui.perplexityInput.addEventListener("change", onSettingsChanged); // recompute P when the slider is released
ui.initSelect.addEventListener("change", onSettingsChanged);
ui.restartButton.addEventListener("click", onSettingsChanged);
ui.runButton.addEventListener("click", () => {
paused = !paused;
ui.runButton.textContent = paused ? "Run" : "Pause";
});
ui.screeCheckbox.addEventListener("change", () => (ui.side.style.display = ui.screeCheckbox.checked ? "flex" : "none"));
await onSettingsChanged();
requestAnimationFrame(animate);

Key points:

  • The 2D map is one XyScatterRenderableSeries with dataIsSortedInX: false. A palette provider's overridePointMarkerArgb colours each point by its class, so 800 or 800,000 points stay a single series.
  • The 3D map is a ScatterRenderableSeries3D with a SpherePointMarker3D; each point's colour goes in its metadata as vertexColor. All three axes share one range so the map isn't stretched.
  • t-SNE runs a few iterations per animation frame, then replaces the points with clear() and appendRange(); with autoRange: EAutoRange.Always the 2D axes follow the map as it grows.
  • The scree plot is a FastColumnRenderableSeries for each component's share of the variance and a FastLineRenderableSeries for the running total.

See it in the demo app: JavaScript scatter chart · React scatter chart · Angular scatter chart, and for a 3D point cloud, JavaScript 3D LiDAR point cloud · React 3D LiDAR point cloud · Angular 3D LiDAR point cloud.

Go deeper: SciChart.js scatter series documentation, the 3D scatter chart documentation, and the guides to the scatter plot, point cloud and correlation matrix, which shows the correlations PCA is built from. For how laboratory and research software uses SciChart, see SciChart for diagnostics and life sciences.

Frequently asked questions​

What is dimensionality reduction in simple terms?​

Dimensionality reduction turns data with many measurements per item into data with only a few, while keeping as much of the useful structure as possible. A photo with thousands of pixel values, or a patient with hundreds of lab results, becomes two or three numbers that can be plotted on a chart or passed to a model. Each method decides differently what to keep: PCA keeps the largest variation, t-SNE and UMAP keep which items are neighbours.

What is the difference between PCA, t-SNE and UMAP?​

PCA is linear: it rotates the data onto the few directions with the most variance, so it is fast, gives the same answer every time and its axes can be interpreted, but it can't unfold curved structure. t-SNE and UMAP are non-linear: they place points so that close neighbours in the original data stay close on the map. They separate clusters far better than PCA, but the sizes of clusters and the gaps between them are not reliable. UMAP is usually faster than t-SNE on large datasets and can map new points.

How many principal components should I keep?​

Plot the explained variance of each component as a scree plot and look for the elbow, where the bars level off; keep the components before it. Alternatively keep enough components to reach a cumulative share of the variance, often 80% to 95%, or keep components whose eigenvalue is above the average. For a 2D or 3D picture you keep two or three regardless, and the cumulative share tells you how much of the data the picture leaves out.

What does perplexity mean in t-SNE?​

Perplexity sets roughly how many neighbours each point pays attention to. t-SNE gives every point a Gaussian over the other points and widens or narrows it until its perplexity, 2 to the power of its entropy, matches the target. Low values focus on very close neighbours and can break real clusters into fragments; high values blend in more distant points and show more of the overall layout. Typical values are 5 to 50, and it is worth comparing several.

Can I trust distances between clusters on a t-SNE plot?​

Not much. t-SNE preserves which points are close to each other, not how far apart separate groups are, and it evens out cluster sizes, so a tight cluster and a spread-out one can look the same size. Two clusters that sit next to each other are usually more similar than two at opposite corners, but the size of the gap is not a measurement. Check any claim about global layout with PCA, or with distances computed in the original space.

How do I plot a PCA or t-SNE embedding in JavaScript?​

Compute the embedding first: for PCA, centre the data, take the eigenvectors of its covariance matrix and project each row onto the first two or three; for t-SNE, run the optimisation for several hundred iterations. Then plot the coordinates as a scatter chart coloured by class, or as a 3D scatter chart for three components. SciChart.js does this with XyScatterRenderableSeries and a palette provider in 2D, and ScatterRenderableSeries3D in 3D, in plain JavaScript, React or Angular.

Sources​