ggumap adds UMAP to ggplot2. geom_umap() and stat_umap() compute a UMAP embedding of the layer data and draw it, in a single step:
library(ggplot2)
library(ggumap)
ggplot(palmerpenguins::penguins, aes(colour = species)) +
geom_umap(features = bill_length_mm:body_mass_g, scale = TRUE, na.rm = TRUE) +
theme_umap()
-
Tidy feature selection. Choose the input columns with
features, usingdplyr::select()syntax. All numeric columns are used by default. -
Any geom.
stat_umap(geom = "text"),"label","density_2d_filled", … Aesthetics are carried along row by row and never split the embedding. - Fast. The computation is done by Apple’s multi-threaded Rust port of umap-learn and PyNNDescent, from embedding-atlas.
- Stable plots. Seeds are derived from the data, and results are cached: re-drawing, resizing or saving a plot does not move the points or recompute the embedding, and several layers share one embedding.
- Facets. One embedding for the whole layer (default) or one per panel.
- Interruptible, with a progress bar for long computations.
Installation
ggumap needs a Rust toolchain (rustc >= 1.90) to build from source; see https://rust-lang.org/tools/install/.
# install.packages("pak")
pak::pak("jeroenjanssens/ggumap")Usage
cars <- transform(mtcars, model = rownames(mtcars))
ggplot(cars, aes(label = model, colour = factor(cyl))) +
geom_umap(scale = TRUE, n_neighbors = 5) +
stat_umap(geom = "text", scale = TRUE, n_neighbors = 5,
size = 2.5, vjust = -0.8, show.legend = FALSE,
check_overlap = TRUE) +
scale_x_continuous(expand = expansion(mult = 0.15)) +
labs(colour = "cylinders") +
theme_umap()
umap_embed() gives you the embedding as a data frame, outside of a plot:
umap_embed(iris, Sepal.Length:Petal.Width, seed = 1) |> head()
#> UMAP1 UMAP2 knn_dist
#> 1 15.77717 -1.391377 0.2206497
#> 2 14.09105 -2.769205 0.2788145
#> 3 14.36441 -2.268250 0.2883166
#> 4 14.15832 -2.540182 0.2761466
#> 5 15.65010 -1.255143 0.2452016
#> 6 16.96546 -1.401339 0.4382381See vignette("ggumap") for more.
Acknowledgements
The UMAP and nearest neighbour implementations are © Apple Inc. (MIT licence), ported from umap-learn and PyNNDescent by Leland McInnes.