To visualize high-dimensional data in 2D, fit sklearn.manifold.TSNE(n_components=2) or umap.UMAP(n_components=2) and scatter the result colored by label. Both keep each point's nearest neighbors close, so local clusters show up clearly. Neither makes the distances between clusters or the sizes of clusters meaningful. The code targets scikit-learn 1.9 and umap-learn 0.6.
Quick Example: PCA vs t-SNE vs UMAP
This uses the 1,797 handwritten digits that ship with scikit-learn (64 pixel features each), so it runs offline. umap-learn is a separate install (pip install umap-learn).
import matplotlib.pyplot as plt
import umap
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
X, y = load_digits(return_X_y=True)
embeddings = {
"PCA": PCA(n_components=2).fit_transform(X),
"t-SNE": TSNE(n_components=2, perplexity=30, random_state=0).fit_transform(X),
"UMAP": umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=0, n_jobs=1,
compatibility_layout=True).fit_transform(X),
}
fig, axes = plt.subplots(1, 3, figsize=(13, 4.4))
for ax, (name, Z) in zip(axes, embeddings.items()):
ax.scatter(Z[:, 0], Z[:, 1], c=y, cmap="tab10", s=7, alpha=0.85, linewidths=0)
ax.set_title(name)
ax.set_xticks([])
ax.set_yticks([])
plt.show()

PCA, which only rotates the data, leaves the digits piled on top of each other. t-SNE and UMAP pull them into ten groups. Both also leave a few small fragments of a digit away from its main cluster (a few orange 1s sit apart from the main 1 cluster in both plots), which is usually a real sub-style of that digit, not an error.
(The compatibility_layout=True and n_jobs=1 arguments are there to keep the output stable and silence two warnings in umap-learn 0.6; see the UMAP section below.)
How Much Better Are They? Measure It
A prettier picture is not evidence. Two numbers make the comparison concrete: sklearn.manifold.trustworthiness (how many of each point's 10 nearest neighbors in 2D were also neighbors in the original 64 dimensions, 1.0 is perfect) and the 5-fold accuracy of a 10-nearest-neighbor classifier trained on just the two embedding coordinates.
from sklearn.manifold import trustworthiness
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
for name, Z in embeddings.items():
trust = trustworthiness(X, Z, n_neighbors=10)
acc = cross_val_score(KNeighborsClassifier(10), Z, y, cv=5).mean()
print(f"{name:6s} trustworthiness {trust:.3f} kNN accuracy {acc:.3f}")
| Method | Fit time | Trustworthiness (k=10) | kNN accuracy on 2 coordinates |
|---|---|---|---|
| PCA | 0.0 s | 0.830 | 0.613 |
| t-SNE | 3.4 s | 0.993 | 0.974 |
| UMAP | 6.5 s | 0.988 | 0.979 |
On this dataset t-SNE and UMAP are effectively tied on quality, and both are far ahead of PCA. Timings are from one run on one laptop with 1,797 points; UMAP is usually the faster of the two as data grows, but here t-SNE was quicker (UMAP's time includes one-off numba compilation, and random_state forces it onto a single thread).
t-SNE: Choose perplexity
TSNE has one parameter that matters, perplexity (default 30), roughly the number of neighbors each point considers. scikit-learn requires it to be less than n_samples. Defaults init="pca" and learning_rate="auto" are already sensible since scikit-learn 1.2.
for p in [2, 5, 30, 100]:
Z = TSNE(perplexity=p, random_state=0).fit_transform(X)

| perplexity | Trustworthiness | kNN accuracy |
|---|---|---|
| 2 | 0.982 | 0.963 |
| 5 | 0.991 | 0.970 |
| 30 | 0.993 | 0.974 |
| 100 | 0.990 | 0.960 |
Very low values fragment clusters into strings, and very high values start pushing neighboring classes together. Anything from about 5 to 50 is a reasonable range for a dataset this size. Try two or three values and trust only the structure that survives all of them.
UMAP: Choose n_neighbors and min_dist
umap.UMAP has two parameters to know. n_neighbors (default 15) sets how local the structure is: small values emphasize fine detail, large values emphasize the broad shape. min_dist (default 0.1) sets how tightly points may pack: 0 gives dense blobs, values near 1 spread points out.

| n_neighbors | min_dist | Trustworthiness | kNN accuracy |
|---|---|---|---|
| 5 | 0.0 | 0.989 | 0.982 |
| 15 | 0.0 | 0.989 | 0.973 |
| 100 | 0.0 | 0.986 | 0.966 |
| 5 | 0.8 | 0.982 | 0.974 |
| 15 | 0.8 | 0.978 | 0.971 |
| 100 | 0.8 | 0.975 | 0.944 |
min_dist=0 makes clusters look tight and well separated, but that is partly cosmetic: the tight blobs at min_dist=0.0 look the most "separate", yet the trustworthiness gain over the spread-out version is small (0.989 vs 0.978 at n_neighbors=15). Use a larger min_dist when you want to see the density of points inside a cluster, and 0 when you plan to cluster the embedding or just need clean separation.
Two things changed in umap-learn 0.6.0 and show up as warnings. A FutureWarning says the default layout pipeline will change, and passing compatibility_layout=True keeps the current one (it was also faster here, 2.2 s against 10.7 s, with the same quality: trustworthiness 0.988 against 0.986). Setting random_state overrides n_jobs to 1, so pass n_jobs=1 to say so explicitly. Drop random_state if you want parallel speed and don't need identical runs.
What You Can and Cannot Read From the Plot
Both methods optimize for keeping neighbors together. That has consequences:
- Cluster separation is real, cluster distance is not. Whether two groups are apart is meaningful. How far apart they are mostly isn't.
- Cluster size and density are not real. t-SNE in particular expands dense regions and shrinks sparse ones.
- The layout changes with the seed. Below, six runs with only the random seed changed:

The same ten clusters appear every time, but which digit sits next to which does not stay put. I checked this by taking the distances between the ten class centers in each embedding and correlating them (Spearman) across runs. Between random-initialized t-SNE runs the correlation was 0.70 to 0.85, and between UMAP runs 0.73 to 0.84. If the global layout were stable, these would be near 1.
It is tempting to say UMAP preserves global structure better than t-SNE. On this dataset I did not find that. Comparing each embedding's class-center distances with those in a 10-component PCA of the original data, t-SNE with the default init="pca" scored 0.81 and with init="random" 0.72 to 0.76, while UMAP scored 0.52 to 0.54. Take that as one dataset and one yardstick, not a general result. The practical point holds either way: do not interpret between-cluster distances in either plot.
One more habit to avoid: do not run K-means or DBSCAN on a 2D t-SNE output and report the clusters as findings. Cluster on the original features or on a PCA reduction (see the K-Means elbow and silhouette post), then use the embedding only to look at the result.
Embedding New Data: UMAP Has transform, t-SNE Does Not
TSNE only has fit_transform; it cannot place new points into an existing map. UMAP can:
from sklearn.model_selection import train_test_split
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
reducer = umap.UMAP(random_state=0, n_jobs=1, compatibility_layout=True).fit(X_tr)
clf = KNeighborsClassifier(10).fit(reducer.embedding_, y_tr)
print(clf.score(reducer.transform(X_te), y_te))
Fitting UMAP on 75% of the digits and transforming the other 25% gave a 10-nearest-neighbor test accuracy of 0.976, in line with the cross-validated figure above. If you need to embed streaming or held-out data, that is the main reason to pick UMAP.
t-SNE vs UMAP: Which Should I Use?
t-SNE (sklearn.manifold.TSNE) |
UMAP (umap.UMAP) |
|
|---|---|---|
| Install | Included in scikit-learn | Separate umap-learn package |
| Key parameters | perplexity |
n_neighbors, min_dist |
| New data | No transform |
transform() available |
| Speed on large data | Slower, scales worse | Usually faster |
| More than 3 dims | Default Barnes-Hut method only allows up to 3 | Fine (n_components=10, for example) |
| Output stability | Changes with seed | Changes with seed |
| Fine for | One-off exploratory plots | Plots plus reusing the embedding as features |
For a quick look at a few thousand points, either works and t-SNE needs no extra dependency. Reach for UMAP when the dataset is large, you need to transform new points, or you want a reduction to more than 2 or 3 dimensions.
Practical Tips
- Standardize or otherwise prepare features first when they are on different scales. The digits here are already on a common scale.
- For wide data (hundreds of features), running
PCA(n_components=50)first speeds both methods and often reduces noise. - Set
random_statewhen you need a reproducible image, and try a couple of seeds before believing any detail. - Color by a label you already know to check the embedding makes sense, as the digit labels do here.
- Report which parameters you used. The same data can be made to look like two clusters or five by changing them.