Visualize Text Embeddings in Python with UMAP and Plotly

Embed a set of texts with a local model, project the vectors to 2D with UMAP, and explore them in an interactive Plotly scatter plot. Includes similarity heatmaps, search, and quality checks.

To visualize text embeddings, turn each text into a vector with an embedding model, reduce the vectors to two dimensions with umap.UMAP(metric="cosine"), and draw them with px.scatter(), using hover text to show what each point is. Texts with similar meaning should land near each other.

Quick Example

The texts here are the first paragraph of 75 docstrings from Matplotlib, pandas, and NumPy, so there's nothing to download besides the model. The embeddings come from EmbeddingGemma 2 (about 380 MB) running locally in Ollama:

ollama pull embeddinggemma-2:270m
pip install ollama umap-learn plotly pandas matplotlib
import inspect

import matplotlib.axes
import numpy as np
import ollama
import pandas as pd
import plotly.express as px
import umap

SOURCES = {
    "Plotting": (matplotlib.axes.Axes, "plot scatter bar barh hist pie boxplot violinplot errorbar "
                                       "fill_between stackplot step imshow contour hexbin"),
    "Text": (pd.Series.str, "lower upper strip split replace contains startswith endswith len pad "
                            "zfill slice cat extract title"),
    "Dates": (pd.Series.dt, "strftime day_name month_name normalize round floor ceil tz_localize "
                            "tz_convert to_period isocalendar to_pydatetime dayofweek is_month_end quarter"),
    "Linear algebra": (np.linalg, "inv det solve eig svd norm qr cholesky pinv matrix_rank lstsq eigh "
                                  "eigvals slogdet matrix_power"),
    "Random sampling": (np.random.Generator, "normal uniform poisson binomial exponential choice shuffle "
                                             "permutation gamma beta integers lognormal multinomial "
                                             "geometric dirichlet"),
}

rows = []
for group, (obj, names) in SOURCES.items():
    for name in names.split():
        paragraphs = inspect.getdoc(getattr(obj, name)).split("\n\n")
        if paragraphs[0].startswith(f"{name}("):  # NumPy's compiled methods open with a signature
            paragraphs = paragraphs[1:]
        rows.append({"group": group, "name": name, "text": " ".join(paragraphs[0].split())})
docs = pd.DataFrame(rows)

MODEL = "embeddinggemma-2:270m"
CLUSTER = "task: clustering | query: "  # the model's prompt prefix for grouping texts

response = ollama.embed(model=MODEL, input=[CLUSTER + t for t in docs["text"]])
vectors = np.array(response.embeddings)
print(vectors.shape)

reducer = umap.UMAP(n_neighbors=10, min_dist=0.2, metric="cosine", random_state=42, n_jobs=1,
                    compatibility_layout=False)  # umap-learn 0.6; remove this argument on 0.5
docs[["x", "y"]] = reducer.fit_transform(vectors)

COLORS = {"Plotting": "#d1495b", "Text": "#00798c", "Dates": "#edae49",
          "Linear algebra": "#30638e", "Random sampling": "#6a4c93"}
fig = px.scatter(docs, x="x", y="y", color="group", color_discrete_map=COLORS,
                 hover_name="name", hover_data={"text": True, "x": False, "y": False, "group": False},
                 template="plotly_white", title="75 docstrings, embedded and mapped with UMAP")
fig.update_traces(marker=dict(size=11, line=dict(width=1, color="white")))
fig.update_xaxes(showticklabels=False, title=None)
fig.update_yaxes(showticklabels=False, title=None)
fig.update_layout(legend_title_text="")
fig.show()

UMAP scatter plot of 75 docstring embeddings, colored by topic: plotting, text, dates, linear algebra and random sampling mostly form separate clusters

Each point is one docstring, and hovering shows its text. The model was never told which library or topic a sentence came from. Plotting, linear algebra, and random sampling form their own clusters, text and dates sit side by side, and three date methods (round, floor, and ceil) break away toward the sampling cluster. The axes have no units, which is why the tick labels are hidden. The run prints (75, 768): one 768-number vector per text.

How Accurate Is the 2D Map?

A 2D layout can't keep every distance from 768 dimensions. One check is to ask, for each text, what share of its 5 nearest neighbors belong to the same group, first with the original vectors and then with the 2D coordinates:

from sklearn.decomposition import PCA
from sklearn.neighbors import NearestNeighbors

groups = docs["group"].to_numpy()


def same_group_share(X, k=5, metric="cosine"):
    neighbors = NearestNeighbors(n_neighbors=k, metric=metric).fit(X).kneighbors()[1]
    return (groups[neighbors] == groups[:, None]).mean()


print(f"768 dimensions: {same_group_share(vectors):.2f}")
print(f"UMAP 2D:        {same_group_share(docs[['x', 'y']], metric='euclidean'):.2f}")
print(f"PCA 2D:         {same_group_share(PCA(2).fit_transform(vectors), metric='euclidean'):.2f}")
768 dimensions: 0.93
UMAP 2D:        0.92
PCA 2D:         0.80

UMAP kept almost all of the neighborhood structure and PCA lost noticeably more of it. This score only measures whether groups stay together. It says nothing about the gaps between clusters, and UMAP and t-SNE both distort those, so don't read "far apart on the map" as "this much less similar."

Show Cosine Similarity as a Heatmap

The heatmap skips dimensionality reduction. EmbeddingGemma returns vectors of length 1, so vectors @ vectors.T gives every pairwise cosine similarity:

import matplotlib.pyplot as plt

similarity = vectors @ vectors.T
edges = np.cumsum([0] + [len(names.split()) for _, names in SOURCES.values()])

heat, ax = plt.subplots(figsize=(7.5, 6.2))
image = ax.imshow(similarity, cmap="magma")
for edge in edges[1:-1]:
    ax.axhline(edge - 0.5, color="white", lw=1)
    ax.axvline(edge - 0.5, color="white", lw=1)
centers = (edges[:-1] + edges[1:]) / 2 - 0.5
ax.set_xticks(centers, SOURCES, rotation=30, ha="right")
ax.set_yticks(centers, SOURCES)
heat.colorbar(image, ax=ax, label="cosine similarity")
ax.set_title("Similarity between every pair of docstrings")
heat.tight_layout()
plt.show()

Heatmap of cosine similarity between 75 docstrings, with brighter square blocks along the diagonal for the five groups

Bright squares along the diagonal are groups whose texts resemble each other. Look at the scale: even the least similar pair scores about 0.72, so compare similarities with each other instead of reading 0.72 as "mostly alike." Find the least cohesive group by averaging the neighbor score within each one:

neighbors = NearestNeighbors(n_neighbors=5, metric="cosine").fit(vectors).kneighbors()[1]
docs["share"] = (groups[neighbors] == groups[:, None]).mean(axis=1)
print(docs.groupby("group", sort=False)["share"].mean().round(2))

for name in ["round", "strftime"]:
    i = docs.index[docs["name"] == name][0]
    print(name, "->", ", ".join(docs["name"].iloc[neighbors[i]]))
group
Plotting           1.00
Text               0.95
Dates              0.73
Linear algebra     1.00
Random sampling    0.96
Name: share, dtype: float64
round -> ceil, floor, choice, hist, permutation
strftime -> upper, lower, title, tz_convert, to_period

Dates is the mixed group. round sits near floor and ceil, then near plotting and sampling functions, and strftime ("Convert to Index using specified date_format") reads more like the string conversions than like a calendar operation. Embeddings group texts by what the words say, and these docstrings don't all mention dates.

Add Search Queries to the Map

The same vectors work for semantic search. EmbeddingGemma has separate prefixes for a search query and for the documents being searched:

doc_vectors = np.array(ollama.embed(
    model=MODEL, input=["title: none | text: " + t for t in docs["text"]]).embeddings)

queries = ["make all the text uppercase", "what day of the week is this date",
           "solve a system of equations", "pick random items from a list"]
query_vectors = np.array(ollama.embed(
    model=MODEL, input=["task: search result | query: " + q for q in queries]).embeddings)

for query, scores in zip(queries, query_vectors @ doc_vectors.T):
    best = np.argsort(-scores)[:3]
    print(f"{query!r}: " + ", ".join(f"{docs['name'][i]} {scores[i]:.2f}" for i in best))
'make all the text uppercase': upper 0.85, title 0.78, strip 0.73
'what day of the week is this date': dayofweek 0.80, isocalendar 0.78, quarter 0.74
'solve a system of equations': solve 0.84, lstsq 0.75, svd 0.69
'pick random items from a list': choice 0.78, permutation 0.73, normal 0.72

Every query finds the right function first. To show where queries fall on the existing map, embed them with the same prefix as the mapped texts and call reducer.transform(), which places new points without moving the old ones:

import plotly.graph_objects as go

as_texts = np.array(ollama.embed(model=MODEL, input=[CLUSTER + q for q in queries]).embeddings)
points = reducer.transform(as_texts)

query_fig = go.Figure(fig)
query_fig.add_trace(go.Scatter(
    x=points[:, 0], y=points[:, 1], mode="markers", name="Search queries",
    hovertext=queries, hoverinfo="text",
    marker=dict(symbol="star", size=18, color="black", line=dict(width=1, color="white"))))
offsets = [(26, 34), (-34, -34), (40, -24), (24, 38)]  # label positions in pixels
for number, ((px_, py_), (ax_, ay_)) in enumerate(zip(points, offsets), 1):
    query_fig.add_annotation(x=px_, y=py_, ax=ax_, ay=ay_, text=f"<b>{number}</b>",
                             bgcolor="white", bordercolor="black", borderpad=3)
query_fig.update_layout(title="Where four search queries land on the map")
query_fig.show()

The same UMAP map with four numbered stars showing where search queries about uppercase text, weekdays, equations and random picks land

The numbered stars are the queries in list order. A star's position is a rough guide only. Rank results with the cosine scores on the full vectors, as above.

Does the Prefix or the Vector Size Matter?

Compare on your own data. Pass dimensions= for shorter vectors, which this model supports at 512, 256, and 128:

plain = np.array(ollama.embed(model=MODEL, input=docs["text"].tolist()).embeddings)
print(f"no prefix: {same_group_share(plain):.3f}")

for size in (768, 512, 256, 128):
    short = np.array(ollama.embed(model=MODEL, input=[CLUSTER + t for t in docs["text"]],
                                  dimensions=size).embeddings)
    print(f"{size} dimensions: {same_group_share(short):.3f}")
no prefix: 0.931
768 dimensions: 0.928
512 dimensions: 0.928
256 dimensions: 0.936
128 dimensions: 0.928

On these 75 short texts neither choice made a meaningful difference: each gap is a handful of the 375 neighbor slots. Shorter vectors take less storage and compare faster, so it's worth testing them on a large collection. Vectors from different models, sizes, or prefixes aren't interchangeable, so embed everything you compare the same way.

UMAP vs t-SNE vs PCA for Embeddings

Method Use it when Watch out for
UMAP You want clusters and may add new points with transform() Layout changes with n_neighbors, min_dist, and the seed
t-SNE You want tight, readable local clusters scikit-learn's TSNE has no transform() for new points
PCA You want a fast, repeatable projection with meaningful axes Two components can hide most of the structure

Practical Tips

  • Set metric="cosine" in UMAP so it measures similarity the way embedding search does.
  • Set random_state to get the same layout on the same machine and library versions. It runs UMAP single-threaded (n_jobs=1).
  • Put the text in hover_data. A cluster plot you can't inspect is hard to trust. See customizing Plotly hover tooltips.
  • Color by a label you already have, such as category or date, to see whether the clusters match it.
  • To use a hosted embedding API instead, only the lines that create vectors change.

Similar Topics