ggutils: a toolbox for ggplot2

smart axis labels, cluster trees, circular layouts and spirals

What ggutils is

ggutils is a ggplot2 extension for everything that sits next to the axis.

ggplot2 draws panels, ticks and legends beautifully, but a few everyday situations still force you into hand-written theme() calls, gtable surgery, or simply giving up: 50 or 200 levels on a discrete axis piling up into an unreadable block; a cluster tree that has to hang beside a discrete axis with its leaves in the same order as the labels; facets where every panel should be scaled to its own data.

ggutils collects those into a handful of guide_*(), scale_*() and facet_*() functions, and it stays inside the ggplot2 idiom — your layers and theme() are untouched, only the axis and facet layer gains something.

What you are facing What to reach for
Crowded categorical labels, you only want a few guide_axis_smart() with n = / which = / nrow =
The labels you kept must point back to their ticks the leader lines of guide_axis_smart() (connection_style)
A cluster tree beside a discrete axis, leaves in label order guide_axis_cluster() / scale_x_cluster() / scale_y_cluster()
Per-panel scales, axes and trees after faceting facet_gridn()
Hundreds of labels that will not fit on a line coord_spiral() / scale_x_spiral_axis()
The tree gets squeezed out of the facet strip strip_cluster()
You only want the layout algorithms box_arrange() / smart_align() / smart_stack()
remotes::install_github("junjunlab/ggutils")

Once installed, one extra guides() line on any plot is enough — see the comparison in the next section.

A suggested reading order: two short sections to see “crowded” versus “not crowded”, then a section per argument of guide_axis_smart(); the y axis, radial coordinates, heatmap annotation and long labels each get their own section; facets and facet_gridn() come next; cluster trees and the known limitations close the document.

The problem: crowded labels

ggplot2 draws a tick and a label for every level of a discrete axis. With many categories (50 samples, 200 features) the labels pile up under the axis: at best they overlap and become unreadable, at worst you delete them and lose the information. Rotating them by 90 degrees helps a little, but long labels and many categories still run off the panel.

set.seed(2024)
df50 <- data.frame(
  sample = factor(paste0("Sample", 1:50), levels = paste0("Sample", 1:50)),
  value = round(runif(50, 10, 100), 1)
)
ggplot(df50, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  labs(x = NULL, y = "response", title = "Default axis: 50 labels in a pile") +
  theme_grey(base_size = 12)
The default x axis with 50 discrete levels: the labels overlap and cannot be read

The default x axis with 50 discrete levels: the labels overlap and cannot be read

ggutils provides guide_axis_smart(). It takes over label drawing on a discrete axis and does three things:

  1. Show only the labels you care about (which = / n =). Every other tick is still connected to its meaning by a leader line, so the correspondence stays obvious.
  2. Spread the labels over several rows (x axis) or columns (y axis) outside the axis, using the page space that a default axis wastes.
  3. Never overlap labels: when there is not enough room it displays fewer labels instead of drawing a pile.

Quick start

Add one guides() line to an existing plot:

ggplot(df50, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(n = 10, nrow = 2)) +
  labs(x = NULL, y = "response", title = "guide_axis_smart(n = 10, nrow = 2)") +
  theme_grey(base_size = 12)
guide_axis_smart(n = 10, nrow = 2): only 10 labels, two staggered rows, each tied back to its tick

guide_axis_smart(n = 10, nrow = 2): only 10 labels, two staggered rows, each tied back to its tick

Only three things change: load the package, add guides(x = guide_axis_smart(...)), keep the rest. Note that you do not need theme(axis.text.x = element_blank()) — the guide draws the labels itself.

Two ways to attach the guide

guide_axis_smart() can go into guides() or into the guide argument of a scale (under coord_flip() the two are not equivalent, see below):

p_guides <- ggplot(df50, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(n = 8, nrow = 2)) +
  labs(x = NULL, y = "response", title = "Style 1: guides(x = guide_axis_smart(...))") +
  theme_grey(base_size = 12)

p_scale <- ggplot(df50, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  scale_x_discrete(guide = guide_axis_smart(n = 8, nrow = 2)) +
  labs(x = NULL, y = "response", title = "Style 2: scale_x_discrete(guide = ...)") +
  theme_grey(base_size = 12)

p_guides
Both spellings give the same plot: guides(x = ...) on top, scale_x_discrete(guide = ...) below

Both spellings give the same plot: guides(x = …) on top, scale_x_discrete(guide = …) below

p_scale
Both spellings give the same plot: guides(x = ...) on top, scale_x_discrete(guide = ...) below

Both spellings give the same plot: guides(x = …) on top, scale_x_discrete(guide = …) below

Parameter reference: what every argument does

The arguments fall into four groups: which labels, how they are laid out, how the leader lines are drawn, and the rest, passed on to guide_axis(). In practice you only touch five of them: which, n, nrow, connection_style and angle.

Parameter Default Meaning
Which labels
which NULL labels to show: integer indices / label text / logical vector / function. NULL shows as many as fit
n NULL maximum number of labels. With which = NULL, n evenly spaced labels are picked; with which, the selection is truncated to n
Layout
nrow NULL number of parallel tracks: rows on an x axis, columns on a y axis. NULL is automatic: one track while everything fits, more only when labels crowd together
padding 0.25 minimum gap between two label boxes in a track, as a fraction of the label height; on a radial axis it is the gap along the arc
gap 0.30 gap between two neighbouring tracks (relative to label height)
extend 0 how far a label may be pushed beyond the axis range (0 to 0.5). 0 keeps every label inside the panel; larger values need enough plot.margin
panel_width NULL panel width (x axis) or height (y axis) in cm, assumed when estimating the number of tracks; NULL estimates it from the device
max_nrow 8L upper bound for the automatic number of tracks
Leader lines
connection TRUE draw leader lines?
connection_style "diagonal" "diagonal" (short stub, diagonal, short stub – the circlize / anno_mark() shape), "straight" (one line), "elbow" (perpendicular plus a shelf)
link_length 3 length in mm of the leader between the axis and the first track; on a radial axis, the distance between the circle and the label
connection_col NULL leader colour; NULL takes the tick colour
connection_lwd 0.5 leader width
connection_lty 1 leader line type
Ticks and text
tick "all" "all" ticks, "shown" only the ticks of drawn labels, "none" no ticks
angle NULL label rotation in degrees; NULL inherits the theme
hjust, vjust NULL label justification inside its box; NULL centres it, which keeps the leader on the visual centre of the text
Radial only
theta_side "outside" labels outside the circle ("outside") or attached to the inner ring of coord_radial(inner.radius =) ("inside")
Passed to guide_axis()
title waiver() axis title
minor.ticks FALSE draw minor ticks
cap "none" axis line end style
order 0 drawing order among guides
position waiver() axis position (top/bottom/left/right); rarely changed
theme NULL theme elements that apply to this guide only

Four combinations that cover most plots:

# 8 genes out of 200, one track
guides(y = guide_axis_smart(which = c("TP53", "EGFR", "MYC", "KRAS",
                                      "BRCA1", "PTEN", "RB1", "ALK")))

# 50 samples, at most 10 labels, staggered over two rows
guides(x = guide_axis_smart(n = 10, nrow = 2))

# long labels, crowded: extra tracks plus longer leader lines
guides(x = guide_axis_smart(which = 1:40, nrow = 3,
                            connection_style = "diagonal", link_length = 5))

# circular heatmap: labels outside the ring, 20 genes only
guides(theta = guide_axis_smart(which = mark, theta_side = "outside"))

Show only the labels you want: four forms of which

which decides which labels are displayed. It accepts four forms:

Form Meaning Example
Integer vector indices into the breaks of the scale which = seq(1, 50, by = 10)
Character vector exact match on the label text which = c("Sample1", "Sample25", "Sample50")
Logical vector one entry per label, TRUE keeps it which = grepl("0$", levels(sample))
Function function(labels, positions) returning a logical vector which = function(labels, positions) positions > 0.45 & positions < 0.55

positions is the relative position of a label inside the panel (0 to 1 along the axis). It does not depend on the data values and is handy for position-based rules.

Integer indices

ggplot(df50, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(which = seq(1, 50, by = 10), nrow = 2)) +
  labs(x = NULL, y = "response", title = "which = seq(1, 50, by = 10)") +
  theme_grey(base_size = 12)
which = seq(1, 50, by = 10): every tenth label

which = seq(1, 50, by = 10): every tenth label

Character vector

ggplot(df50, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(
    which = c("Sample1", "Sample2", "Sample25", "Sample50"),
    nrow = 1
  )) +
  labs(x = NULL, y = "response", title = "Match label text: which = c(\"Sample1\", \"Sample2\", \"Sample25\", \"Sample50\")") +
  theme_grey(base_size = 12)
Matching label text: the four labels Sample1, Sample2, Sample25 and Sample50

Matching label text: the four labels Sample1, Sample2, Sample25 and Sample50

Logical vector

ggplot(df50, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(
    which = grepl("0$", levels(df50$sample)),
    nrow = 1
  )) +
  labs(x = NULL, y = "response", title = "Logical vector: which = grepl(\"0$\", levels(sample))") +
  theme_grey(base_size = 12)
A logical vector: only samples whose number ends in 0

A logical vector: only samples whose number ends in 0

Function

When which is a function, it is called with the label texts and the relative positions and must return a logical vector (index vectors are also accepted). The example keeps every tenth label:

ggplot(df50, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(
    which = function(labels, positions) seq_along(labels) %% 10 == 1,
    nrow = 2
  )) +
  labs(x = NULL, y = "response", title = "Function: every tenth label") +
  theme_grey(base_size = 12)
which = function(labels, positions) seq_along(labels) %% 10 == 1: every tenth label

which = function(labels, positions) seq_along(labels) %% 10 == 1: every tenth label

The function form is most useful for position-based selection: positions runs from 0 to 1, so positions > 0.9 keeps only the right-hand end of the axis.

Automatic selection: n

If you do not want to compute indices, just cap the number of labels:

ggplot(df50, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(n = 5)) +
  labs(x = NULL, y = "response", title = "n = 5 (evenly spaced)") +
  theme_grey(base_size = 12)
n = 5: five evenly spaced labels, one row is enough

n = 5: five evenly spaced labels, one row is enough

ggplot(df50, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(n = 20)) +
  labs(x = NULL, y = "response", title = "n = 20 (rows added automatically)") +
  theme_grey(base_size = 12)
n = 20: 20 labels, split over two rows when one row is not enough

n = 20: 20 labels, split over two rows when one row is not enough

When both which and n are given, which selects first and n then truncates the result to at most n labels, evenly spaced (n is a hard cap). With which = NULL, n picks evenly from all labels directly.

Automatic behaviour: what happens when you pass nothing

How the number of tracks (rows/columns) is chosen: one row whenever the labels fit — they stretch along the axis, which gives short leader lines and the closest match to the anno_mark() look. More tracks are only added when the total width of the labels exceeds one row. If the labels crowd into a small stretch of the axis, the guide splits them over several rows even when their total width is small, using the span of that cluster, so that long crossing diagonals are avoided. At most max_nrow tracks (default 8) are used.

With which = NULL and n = NULL the guide displays all labels by default. If the total width exceeds what max_nrow tracks can hold, the guide thins the labels out evenly and prints a single cli message, for example:

set.seed(1)
df200 <- data.frame(
  feature = factor(paste0("Feature", 1:200), levels = paste0("Feature", 1:200)),
  value = runif(200)
)

ggplot(df200, aes(x = feature, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.9) +
  guides(x = guide_axis_smart()) +
  labs(x = NULL, y = "importance", title = "200 categories: automatic thinning") +
  theme_grey(base_size = 12)
#> ℹ Only 88 of 200 labels fit into 8 tracks; 112 labels are not displayed.
#> ℹ Set `nrow` or `which` in `guide_axis_smart()` to control this.
200 categories with neither which nor n: thinning keeps the plot readable, but fewer labels are shown

200 categories with neither which nor n: thinning keeps the plot readable, but fewer labels are shown

To silence that message (for example when plotting in a loop), set options(ggutils.quiet = TRUE). Still, always prefer an explicit n = or which = so that you decide which labels are shown, rather than the screen size.

Staggering over rows: nrow, gap, padding

nrow controls how many rows the x axis labels occupy below the axis; NULL (the default) means automatic — one row whenever it fits, more rows only when the labels crowd or overflow. gap is the space between rows (default 0.30) and padding the minimum space between neighbouring label boxes in one row (default 0.25); both are relative to the label height.

ggplot(df50, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(n = 8, nrow = 1)) +
  labs(x = NULL, y = "response", title = "n = 8, nrow = 1") +
  theme_grey(base_size = 12)
nrow = 1: everything in one row, the labels must fit

nrow = 1: everything in one row, the labels must fit

ggplot(df50, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(n = 24, nrow = 3)) +
  labs(x = NULL, y = "response", title = "n = 24, nrow = 3") +
  theme_grey(base_size = 12)
nrow = 3: three staggered rows; more vertical space means more labels

nrow = 3: three staggered rows; more vertical space means more labels

ggplot(df50, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(n = 30)) +
  labs(x = NULL, y = "response", title = "n = 30, nrow = NULL (automatic rows)") +
  theme_grey(base_size = 12)
nrow = NULL: one row when it fits, otherwise rows are added automatically

nrow = NULL: one row when it fits, otherwise rows are added automatically

Rules of thumb:

ggplot(df50, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(n = 16, nrow = 2, gap = 0.5, padding = 0.6)) +
  labs(x = NULL, y = "response", title = "gap = 0.5, padding = 0.6") +
  theme_grey(base_size = 12)
gap = 0.5, padding = 0.6: more space between rows and boxes

gap = 0.5, padding = 0.6: more space between rows and boxes

y axis (vertical discrete axis)

Map the discrete variable to the y axis. Note that nrow means columns on a y axis: the labels are spread over several columns outside the axis, and the outermost column holds the labels that are pushed furthest out.

labs40 <- paste0("Sample", 1:40)
df40 <- data.frame(
  sample = factor(labs40, levels = rev(labs40)),
  value = round(runif(40, 10, 100), 1)
)

ggplot(df40, aes(x = value, y = sample)) +
  geom_col(fill = "#F6903D", width = 0.8) +
  guides(y = guide_axis_smart(n = 10, nrow = 2)) +
  labs(x = "response", y = NULL, title = "y axis: n = 10, nrow = 2 (2 columns)") +
  theme_grey(base_size = 12)
y axis: nrow = 2 spreads the labels over 2 columns

y axis: nrow = 2 spreads the labels over 2 columns

ggplot(df40, aes(x = value, y = sample)) +
  geom_col(fill = "#F6903D", width = 0.8) +
  guides(y = guide_axis_smart(which = seq(1, 40, by = 4), nrow = 3)) +
  labs(x = "response", y = NULL, title = "y axis: which = seq(1, 40, by = 4), nrow = 3") +
  theme_grey(base_size = 12)
y axis: nrow = 3, three columns make room for more labels

y axis: nrow = 3, three columns make room for more labels

Radial coordinates: coord_radial()

coord_radial() renames the position scales to theta and r, so the guide is attached with guides(theta = ...). On this axis ggutils lays the labels out the way circlize::circos.labels() does: the text runs along the radius and points towards the centre of the circle (turned around on the left half), crowded labels are spread along the arc with the smartAlign algorithm, and every label is tied to its tick by a three-segment leader line (radial stub, diagonal, radial stub).

ggplot(df50, aes(sample, value)) +
  geom_col() +
  coord_radial(theta = "x") +
  guides(theta = guide_axis_smart(which = seq(1, 50, by = 4)))
coord_radial(theta = 'x'): a circular bar chart, every 4th label

coord_radial(theta = ‘x’): a circular bar chart, every 4th label

ggplot(df50, aes(sample, value)) +
  geom_col() +
  coord_radial(theta = "x") +
  guides(theta = guide_axis_smart(which = 9:20))
12 crowded labels: spread along the arc and connected with three-segment leader lines

12 crowded labels: spread along the arc and connected with three-segment leader lines

ggplot(df50, aes(value, sample)) +
  geom_col() +
  coord_radial(theta = "y") +
  guides(theta = guide_axis_smart(n = 10))
categories mapped to y with theta = 'y' work the same way

categories mapped to y with theta = ‘y’ work the same way

ggplot(df50, aes(sample, value)) +
  geom_col() +
  coord_radial(theta = "x", start = -0.5 * pi, end = 0.5 * pi) +
  guides(theta = guide_axis_smart(which = 9:20))
a half circle (start/end) is laid out the same way

a half circle (start/end) is laid out the same way

Circular heatmaps: labels outside or inside

With the bundled data (300 genes x 8 samples) the theta axis is the gene axis:

data(airway_heatmap)
ggplot(airway_sample_z, aes(gene, sample, fill = z_sample)) +
  geom_tile() +
  coord_radial(theta = "x", inner.radius = 0.2) +
  guides(theta = guide_axis_smart(which = airway_heatmap$mark)) +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                       midpoint = 0, name = "z-score (sample)")
circular heatmap with the labels outside: the crowded gene cluster spreads along the outer arc

circular heatmap with the labels outside: the crowded gene cluster spreads along the outer arc

With a large inner radius the labels can go inside the hole (theta_side = "inside"), attached to the inner radius:

ggplot(airway_sample_z, aes(gene, sample, fill = z_sample)) +
  geom_tile() +
  coord_radial(theta = "x", inner.radius = 0.62) +
  guides(theta = guide_axis_smart(
    which = airway_heatmap$mark, theta_side = "inside"
  )) +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                       midpoint = 0, name = "z-score (sample)")
#> Only 18 of 20 labels fit around the ring; 2 were dropped. Use `which` / `n` or
#> a larger device.
circular heatmap with the labels inside: theta_side = 'inside', attached to the inner radius

circular heatmap with the labels inside: theta_side = ‘inside’, attached to the inner radius

Facets: one circle per panel

With facet_wrap() / facet_grid() every panel is its own circle and lays its labels out independently:

d_facet <- data.frame(
  panel = rep(c("A", "B", "C", "D"), each = 20),
  cat   = factor(rep(paste0("g", 1:20), 4), levels = paste0("g", 1:20)),
  value = round(runif(80, 5, 100), 1)
)
ggplot(d_facet, aes(cat, value)) +
  geom_col(fill = "#3b82f6") +
  coord_radial(theta = "x") +
  guides(theta = guide_axis_smart(which = seq(1, 20, by = 2))) +
  facet_wrap(~panel)
facet_wrap + coord_radial: one circle per panel, every 2nd label

facet_wrap + coord_radial: one circle per panel, every 2nd label

d_free <- data.frame(
  panel = c(rep("A", 20), rep("B", 30)),
  cat   = factor(c(paste0("a", 1:20), paste0("b", 1:30))),
  value = round(runif(50, 5, 100), 1)
)
ggplot(d_free, aes(cat, value)) +
  geom_col(fill = "#f97316") +
  coord_radial(theta = "x") +
  guides(theta = guide_axis_smart(which = 1:6)) +
  facet_wrap(~panel, scales = "free_x")
facet_wrap + free_x: each panel labels its own first 6 categories

facet_wrap + free_x: each panel labels its own first 6 categories

d_crowd <- data.frame(
  panel = rep(c("set1", "set2"), each = 40),
  gene  = factor(rep(paste0("gene", 1:40), 2)),
  value = round(runif(80, 5, 100), 1)
)
ggplot(d_crowd, aes(gene, value)) +
  geom_col(fill = "#8b5cf6") +
  coord_radial(theta = "x") +
  guides(theta = guide_axis_smart(which = c(5:16, 25:30))) +
  facet_wrap(~panel)
a crowded cluster in every panel: spread independently per panel

a crowded cluster in every panel: spread independently per panel

For a faceted circular heatmap add scales = "free_x": each panel then uses its own gene scale, so the ring is complete and the labels only land on the genes that panel actually contains:

ggplot(airway_sample_z, aes(gene, sample, fill = z_sample)) +
  geom_tile() +
  coord_radial(theta = "x", inner.radius = 0.3) +
  guides(theta = guide_axis_smart(which = unlist(airway_heatmap$mark_by_set))) +
  facet_wrap(~gene_set, ncol = 2, scales = "free_x") +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                       midpoint = 0, name = "z-score (sample)")
faceted circular heatmap + free_x: complete rings, each panel labels its own 4 genes

faceted circular heatmap + free_x: complete rings, each panel labels its own 4 genes

Without scales = "free_x" the panels share one theta scale: half of each ring stays empty and the 8 genes picked by which are labelled in both panels.

Radial labels inherit the theme’s axis text style (axis.text.x / axis.text.y: size, colour, family, …) exactly like the stock axis labels.

Local annotations and heatmap labels (anno_mark style)

The "diagonal" geometry matches circlize and ComplexHeatmap::anno_mark() exactly: short stub, diagonal, short stub, text. Together with the track strategy (“one row when it fits, clustered labels split into tracks”) this is ideal for labelling only a few categories of interest.

Labels that sit in one stretch of the axis: automatic tracks

If the labels selected by which only occupy a small stretch of the axis, the guide splits them over several rows with vertical staggering, and every label still connects to its own tick:

set.seed(5)
labs60 <- paste0("Sample", 1:60)
df60 <- data.frame(
  sample = factor(labs60, levels = labs60),
  value = round(runif(60, 10, 100), 1)
)

ggplot(df60, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(which = 24:35)) +
  labs(x = NULL, y = "response", title = "which = 24:35 (several rows)") +
  theme_grey(base_size = 12)
only labels 24-35 of 60 categories: split over several rows automatically

only labels 24-35 of 60 categories: split over several rows automatically

To force the single-row, pure anno_mark look (labels stretched along the axis, longer leader lines), write nrow = 1:

ggplot(df60, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(which = 24:35, nrow = 1)) +
  labs(x = NULL, y = "response", title = "which = 24:35, nrow = 1 (anno_mark style)") +
  theme_grey(base_size = 12)
#> ! The requested nrow = 1 is probably too small for 12 labels: some of them will
#>   not be drawn.
#> ℹ Increase `nrow`, or select fewer labels with `which` / `n`.
the same labels with nrow = 1: stretched along the axis, longer leader lines

the same labels with nrow = 1: stretched along the axis, longer leader lines

Heatmap labels: sec.axis + dup_axis()

“Label only a few rows and hide the rest” is the typical anno_mark() use case. Switch the main axis off, duplicate it with dup_axis(), and attach the smart guide to the copy.

This section uses the data set bundled with the package, airway_heatmap: real RNA-seq from GEO (GSE52778; human airway smooth muscle cells, four cell lines with and without dexamethasone). The data is already processed — expressed genes only, log2(CPM + 1), the 300 most variable genes; heatmap examples below use per-sample z-scores (each sample standardised across the genes), ordered by hierarchical clustering (see ?airway_heatmap for the exact steps) — so the chunks below load it and plot immediately.

To make the leader lines and the vertical distribution of the labels visible, the heatmap shows 300 genes and labels 20 of them (12 neighbouring genes from the top response cluster plus 8 scattered genes):

## bundled data: 300 genes x 8 samples, per-sample z-scores for the heat maps
data(airway_heatmap, package = "ggutils")
df_gene <- airway_sample_z
mark    <- airway_heatmap$mark
ggplot(df_gene, aes(x = sample, y = gene, fill = z_sample)) +
  geom_tile() +
  scale_y_discrete(
    guide = guide_none(),
    sec.axis = dup_axis(
      guide = guide_axis_smart(which = mark)
    )
  ) +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                       midpoint = 0, name = "z-score (sample)") +
  labs(x = NULL, y = NULL, title = "airway RNA-seq (GEO GSE52778), 300 genes") +
  theme_grey(base_size = 9) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
real data (GEO GSE52778), a tall 300-gene heatmap: only 20 genes are labelled, showing how the leader lines and the vertical label spacing are allocated

real data (GEO GSE52778), a tall 300-gene heatmap: only 20 genes are labelled, showing how the leader lines and the vertical label spacing are allocated

When the heatmap is faceted, every panel holds different data and lays out its own labels. Here the genes are split into an “up” and a “down” panel, and each panel labels only its four strongest responders (panel heights follow the number of genes):

## the four strongest responders of each gene set are precomputed in the data
mark_facet <- unlist(airway_heatmap$mark_by_set, use.names = FALSE)

ggplot(df_gene, aes(x = sample, y = gene, fill = z_sample)) +
  geom_tile() +
  facet_grid(gene_set ~ ., scales = "free_y", space = "free_y", switch = "y") +
  scale_y_discrete(
    position = "right",
    guide = guide_axis_smart(
      which = function(labels, positions) labels %in% mark_facet
    )
  ) +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                       midpoint = 0, name = "z-score (sample)") +
  labs(x = NULL, y = NULL, title = "facet by gene set, 300 genes") +
  theme_grey(base_size = 9) +
  theme(panel.grid = element_blank(),
        strip.placement = "outside",
        strip.text.y.left = element_text(angle = 0),
        axis.text.x = element_text(angle = 45, hjust = 1))
faceted heatmap: each panel has different data and lays out its own labels

faceted heatmap: each panel has different data and lays out its own labels

Key points:

Long labels and angles: angle, hjust, vjust

When the label text is long (for example “Sample12 (Treated A)”), staggering over rows may still not be enough; rotate the labels instead. angle accepts 0, 45 and 90; NULL (the default) inherits the angle from axis.text.x in the theme.

trt <- rep(c("Control", "Treated A", "Treated B"), 8)
labs24 <- paste0("Sample", 1:24, " (", trt, ")")
df24 <- data.frame(
  sample = factor(labs24, levels = labs24),
  value = round(runif(24, 10, 100), 1)
)

ggplot(df24, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(n = 12, nrow = 2)) +
  labs(x = NULL, y = "response", title = "Long labels, staggered rows: n = 12, nrow = 2") +
  theme_grey(base_size = 12)
#> ! The requested nrow = 2 is probably too small for 12 labels: some of them will
#>   not be drawn.
#> ℹ Increase `nrow`, or select fewer labels with `which` / `n`.
long labels with staggered rows (no rotation): n = 12, nrow = 2

long labels with staggered rows (no rotation): n = 12, nrow = 2

ggplot(df24, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(n = 12, nrow = 1, angle = 45, hjust = 1, vjust = 1)) +
  labs(x = NULL, y = "response", title = "angle = 45, hjust = 1, vjust = 1") +
  theme_grey(base_size = 12)
#> ! The requested nrow = 1 is probably too small for 12 labels: some of them will
#>   not be drawn.
#> ℹ Increase `nrow`, or select fewer labels with `which` / `n`.
angle = 45 with nrow = 1, hjust = 1 and vjust = 1

angle = 45 with nrow = 1, hjust = 1 and vjust = 1

ggplot(df24, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(n = 12, nrow = 1, angle = 90, hjust = 1, vjust = 0.5)) +
  labs(x = NULL, y = "response", title = "angle = 90, hjust = 1, vjust = 0.5") +
  theme_grey(base_size = 12)
angle = 90 with hjust = 1 and vjust = 0.5

angle = 90 with hjust = 1 and vjust = 0.5

hjust / vjust are passed to the label text grob; with NULL the guide picks a sensible value for the angle. In practice:

Continuous axes work too

guide_axis_smart() does not require a discrete axis. With scale_*_continuous(breaks = ...) you can request many ticks and then show only a subset, over one or several rows:

set.seed(2024)
df_curve <- data.frame(
  x = seq(0, 100, length.out = 200),
  y = sin(seq(0, 100, length.out = 200) / 12) + rnorm(200, sd = 0.15)
)

ggplot(df_curve, aes(x, y)) +
  geom_line(colour = "#5B8FF9", linewidth = 0.8) +
  scale_x_continuous(breaks = seq(0, 100, by = 2), minor_breaks = NULL) +
  guides(x = guide_axis_smart(n = 10)) +
  labs(x = NULL, y = "response", title = "Continuous axis: 51 ticks, only 10 labels") +
  theme_grey(base_size = 12)
continuous axis: 51 tick labels, only 10 displayed

continuous axis: 51 tick labels, only 10 displayed

On a continuous axis the character form of which matches the formatted tick text (e.g. "20"); for position-based rules the function form is more robust.

Working with facets, coord_flip and themes

facet: each panel lays out its own labels

Facetting gives every panel its own axis; the guide does its layout independently in each panel (a narrower panel may need more rows), and each panel only picks labels from its own breaks.

set.seed(7)
df_facet <- data.frame(
  sample = factor(paste0("Sample", 1:30), levels = paste0("Sample", 1:30)),
  value = round(runif(60, 10, 100), 1),
  group = rep(c("Group A", "Group B"), each = 30)
)

ggplot(df_facet, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  facet_wrap(~ group, scales = "free_x") +
  guides(x = guide_axis_smart(n = 6, nrow = 2)) +
  labs(x = NULL, y = "response", title = "facet_wrap: independent layout per panel") +
  theme_grey(base_size = 12)
facet_wrap: each panel lays out its labels independently

facet_wrap: each panel lays out its labels independently

Free scales: each panel labels only what it contains

With scales = "free_x" (or free_y) every panel carries different categories. Write all the labels you want to mark once in which; each panel only draws the ones it actually has, and labels that are not present in a panel are skipped silently (no error, no warning per panel):

set.seed(8)
df_facet_free <- data.frame(
  cat = factor(
    c(paste0("A", 1:15), paste0("B", 1:15), paste0("C", 1:15), paste0("D", 1:15)),
    levels = c(paste0("A", 1:15), paste0("B", 1:15), paste0("C", 1:15), paste0("D", 1:15))
  ),
  value = round(runif(60, 10, 100), 1),
  group = rep(c("Group A", "Group B", "Group C", "Group D"), each = 15)
)
mark_facet_free <- c("A3", "A4", "A5", "A6", "B10", "C1", "C8", "D12")

ggplot(df_facet_free, aes(cat, value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  facet_wrap(~ group, nrow = 2, scales = "free_x") +
  guides(x = guide_axis_smart(which = mark_facet_free)) +
  labs(x = NULL, y = "response",
       title = "facet_wrap + free_x: each panel labels what it has") +
  theme_grey(base_size = 11)
facet_wrap + free_x: each panel labels only its own categories

facet_wrap + free_x: each panel labels only its own categories

Crowded labels inside one panel

A run of neighbouring labels is spread over several rows inside that panel; the narrower the panel, the more rows are used. Here nrow = 3 is forced:

df_facet_crowd <- data.frame(
  cat = factor(paste0("c", 1:20), levels = paste0("c", 1:20)),
  value = rep(c(15, 62, 23, 78, 34, 51, 44, 29), length.out = 40),
  group = rep(c("Group A", "Group B"), each = 20)
)

ggplot(df_facet_crowd, aes(cat, value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  facet_wrap(~ group, nrow = 1) +
  guides(x = guide_axis_smart(which = 3:14, nrow = 3)) +
  labs(x = NULL, y = "response",
       title = "crowded labels inside a panel: 3 rows") +
  theme_grey(base_size = 11)
12 crowded labels inside a panel: spread over 3 rows

12 crowded labels inside a panel: spread over 3 rows

facet_grid: a shared axis is drawn once, free axes once per panel

With facet_grid and a shared x axis the guide is drawn once; with scales = "free_x" every column gets its own:

df_facet_grid <- data.frame(
  cat = factor(c(paste0("g", 1:15), paste0("h", 1:15)),
               levels = c(paste0("g", 1:15), paste0("h", 1:15))),
  value = round(runif(30, 10, 100), 1),
  side = rep(c("left panel", "right panel"), each = 15)
)

ggplot(df_facet_grid, aes(cat, value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  facet_grid(. ~ side, scales = "free_x") +
  guides(x = guide_axis_smart(which = c("g2", "g7", "g12", "h3", "h9", "h14"))) +
  labs(x = NULL, y = "response",
       title = "facet_grid + free_x: each column labels its own") +
  theme_grey(base_size = 11)
facet_grid + free_x: each column labels its own categories

facet_grid + free_x: each column labels its own categories

Faceted heatmap: the right-hand y axis is labelled per panel

For a faceted heatmap attach the guide with scale_y_discrete(position = "right"); with free_y each panel labels only the genes it contains, and a crowded run of genes is spread over rows inside that panel:

## the real RNA-seq data bundled with the package (GEO GSE52778, 300 genes x 8 samples)
data(airway_heatmap, package = "ggutils")
df_facet_heat <- airway_sample_z
mark_wrap <- airway_heatmap$genes$gene[10:21]   # 12 neighbouring genes of the top cluster

ggplot(df_facet_heat, aes(sample, gene, fill = z_sample)) +
  geom_tile() +
  facet_wrap(~ gene_set, nrow = 1, scales = "free_y") +
  scale_y_discrete(
    position = "right",
    guide = guide_axis_smart(which = mark_wrap)
  ) +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                       midpoint = 0, name = "z-score (sample)") +
  labs(x = NULL, y = NULL,
       title = "faceted heatmap: each panel labels its own genes") +
  theme_grey(base_size = 9) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
faceted heatmap: the bundled real data, each panel labels its own genes

faceted heatmap: the bundled real data, each panel labels its own genes

Facet checklist

  • both facet_wrap and facet_grid work; the guide lays out inside every panel;
  • free_x / free_y: each panel draws only the labels it has, so a single which can cover all panels;
  • shared scales: the axis is drawn once (facet_grid rows share x, columns share y);
  • crowding: a narrower panel uses more rows automatically, or force it with nrow;
  • facets + dup_axis() do not work (the copy is not drawn per panel); attach the guide with scale_*_discrete(position =, guide =) instead.

theme: text styles are inherited

Colour, size, font family and face of the labels are inherited from axis.text.x / axis.text.y, so theme() code keeps working:

ggplot(df50, aes(x = sample, y = value)) +
  geom_col(fill = "#5B8FF9", width = 0.8) +
  guides(x = guide_axis_smart(n = 12, nrow = 2)) +
  labs(x = NULL, y = "response", title = "Label style inherited from the theme") +
  theme_grey(base_size = 13) +
  theme(axis.text.x = element_text(colour = "grey30", size = 9))
label style inherited from axis.text.x: grey, 9 pt

label style inherited from axis.text.x: grey, 9 pt

Do not use theme(axis.text.x = element_blank()) — the guide inherits that blank element verbatim and all labels disappear.

facet_gridn(): a per-panel facet_grid

facet_grid(scales = "free_x") frees x per column: panels stacked in the same column still share one x axis, because the layout sets SCALE_X to the column index. facet_gridn() lays the panels out exactly the same way (rows and columns, row strips on the right, column strips on top) but sets SCALE_X / SCALE_Y to the panel index, so every cell trains its own scale, gets its own range and its own axis.

scales freedom x axis y axis
"fixed" shared (default) one global axis one global axis
"free_x" per panel one axis per panel one global axis
"free_y" per panel one global axis one axis per panel
"free" per panel one axis per panel one axis per panel
"free_x_bycol" same as facet_grid() one axis per column one global axis
"free_y_byrow" same as facet_grid() one global axis one axis per row

The last two are compatibility values: free_x_bycol / free_y_byrow are exactly the stock free_x / free_y, which is what you want when one figure has to mix both kinds of freedom (x shared per column, y independent per panel). scales = "fixed" matches facet_grid() pixel for pixel and can be swapped in at any time.

All examples below use mpg (drv: 3 rows x year: 2 columns = 6 panels):

library(patchwork)
#> Warning: package 'patchwork' was built under R version 4.5.3
d_cont <- mpg
d_disc <- mpg
d_disc$cylgrp <- factor(ifelse(d_disc$cyl == 4, "4 cyl", "6 / 8 cyl"),
                        levels = c("4 cyl", "6 / 8 cyl"))
th_n <- theme_bw(base_size = 9) +
  theme(panel.grid.minor = element_blank(),
        strip.text = element_text(size = 8),
        axis.text = element_text(size = 7),
        plot.title = element_text(size = 9))
p_cont_n <- function(scales, fn = facet_gridn) {
  ggplot(d_cont, aes(displ, hwy)) +
    geom_point(size = 1.2, alpha = 0.8) +
    fn(vars(drv), vars(year), scales = scales) +
    labs(title = scales, x = NULL, y = NULL) + th_n
}

Continuous axes: the four modes side by side

(p_cont_n("fixed")  | p_cont_n("free_x")) /
  (p_cont_n("free_y") | p_cont_n("free"))
continuous axes, four scales: fixed shares everything, free_x / free_y free one direction per panel, free frees both

continuous axes, four scales: fixed shares everything, free_x / free_y free one direction per panel, free frees both

With free_x every panel carries its own tick labels underneath, with free_y every panel has its own ticks on the left, and free has both. The difference is measurable: on the same data the stock facet_grid(scales = "free_x") produces only 2 distinct x ranges (one per column), facet_gridn() produces 6 (one per panel); free_y is the mirror image – 3 for stock (one per row), 6 for facet_gridn().

Categorical x: every panel keeps only its own categories

In mpg, 2seater only occurs in the r row and minivan only in the f row, which makes “each panel keeps only its own categories” easy to see:

p_catx_n <- function(fn = facet_gridn) {
  ggplot(d_cont, aes(class, hwy)) +
    geom_boxplot(fill = "grey92", linewidth = 0.3, outlier.size = 0.8) +
    fn(vars(drv), vars(year), scales = "free_x") +
    th_n + theme(axis.text.x = element_text(angle = 45, hjust = 1))
}
p_catx_n()
facet_gridn(scales = 'free_x'): each panel's x axis lists only the categories it contains

facet_gridn(scales = ‘free_x’): each panel’s x axis lists only the categories it contains

p_catx_n(facet_grid)
the same data with facet_grid(scales = 'free_x'): the x axis only sits under the bottom row, and a column shares its union

the same data with facet_grid(scales = ‘free_x’): the x axis only sits under the bottom row, and a column shares its union

Compare the two: with facet_gridn() each panel’s x categories are exactly the ones that occur in that cell, while stock uses the union of the whole column, so the 1999 cell of the f column still reserves a slot for minivan even though it has no data there.

Categorical y: the same rule, other direction

p_caty_n <- function(fn = facet_gridn) {
  ggplot(d_cont, aes(hwy, class)) +
    geom_boxplot(fill = "grey92", linewidth = 0.3, outlier.size = 0.8) +
    fn(vars(year), vars(drv), scales = "free_y") +
    th_n
}
p_caty_n()
facet_gridn(scales = 'free_y'): each panel lists only its own categories on the left, with its own y axis

facet_gridn(scales = ‘free_y’): each panel lists only its own categories on the left, with its own y axis

p_caty_n(facet_grid)
facet_grid(scales = 'free_y'): the y axis only sits in the left-most column, and a row shares its union

facet_grid(scales = ‘free_y’): the y axis only sits in the left-most column, and a row shares its union

Discrete on both axes: everything per panel

p_disc_n <- function(fn = facet_gridn) {
  ggplot(d_disc, aes(class, drv)) +
    geom_count(colour = "grey25", alpha = 0.85) +
    scale_size_area(max_size = 6) +
    fn(vars(year), vars(cylgrp), scales = "free") +
    th_n + theme(axis.text.x = element_text(angle = 45, hjust = 1))
}
p_disc_n()
facet_gridn(scales = 'free'): both axes of every cell list only the categories it contains

facet_gridn(scales = ‘free’): both axes of every cell list only the categories it contains

p_disc_n(facet_grid)
facet_grid(scales = 'free'): x per column, y per row, leaving unused categories on the axes

facet_grid(scales = ‘free’): x per column, y per row, leaving unused categories on the axes

Counted per panel, the axis labels are x 6 / 7 / 5 / 7 and y 2 / 3 / 2 / 3 for facet_gridn(), versus x 6 / 7 / 6 / 7 and y 3 / 3 / 3 / 3 for stock: the 2008 cells have no minivan and the 4-cylinder cells have no rear-wheel drive, and only facet_gridn() drops them from the axis.

Panels in rows: rows = vars(drv)

Put the facet variable on rows and the layout becomes three rows of one column; free_y gets easier to see, since each row draws only its own y range:

ggplot(d_cont, aes(displ, hwy)) +
  geom_point(size = 1.2, alpha = 0.8) +
  facet_gridn(rows = vars(drv), cols = vars(year), scales = "free_y",
              space = "free_y") +
  th_n
rows = vars(drv), scales = 'free_y': every panel gets its own y axis

rows = vars(drv), scales = ‘free_y’: every panel gets its own y axis

space = "free_y" hands each row a height proportional to its y range; switch back to scales = "fixed" for a shared axis.

space = "free_x": panel width follows its own range

ggplot(d_cont, aes(displ, hwy)) +
  geom_point(size = 1.2, alpha = 0.8) +
  facet_gridn(vars(drv), vars(year), scales = "free_x", space = "free_x") +
  th_n
space = 'free_x': a wider x range gets a wider panel

space = ‘free_x’: a wider x range gets a wider panel

r/2008 is clearly wider than f/1999. Careful: per-panel axes make the tick labels differ in width from row to row, so column borders can drift slightly out of alignment; keep the default space = "fixed" for a strictly tabular layout.

Compatibility values: free_x_bycol / free_y_byrow

To keep the stock “per column / per row” semantics (say x shared per column but y independent per panel), use these two values:

p_cont_n("free_x_bycol")
free_x_bycol: the x axis only sits under the bottom row and is shared per column -- identical to facet_grid(scales = 'free_x')

free_x_bycol: the x axis only sits under the bottom row and is shared per column – identical to facet_grid(scales = ‘free_x’)

free_y_byrow is the mirror image (y only in the left-most column, shared per row) and matches the stock free_y.

p_cont_n("free_y_byrow")
free_y_byrow: the y axis only sits on the left-most column and is shared per row -- identical to facet_grid(scales = 'free_y')

free_y_byrow: the y axis only sits on the left-most column and is shared per row – identical to facet_grid(scales = ‘free_y’)

Combining with the cluster tree

scale_x_cluster() / scale_y_cluster() read the facet’s scales themselves, so switching to facet_gridn() makes the trees per panel as well: one tree per cell, without touching any tree-related code. See “Cluster dendrogram on a discrete axis” below for the examples.

Spiral coordinates: coord_spiral()

coord_spiral() bends an ordinary Cartesian ggplot into an Archimedean spiral. The geometry follows the spiralize package: the base spiral is r = b·theta and one turn increases the radius by one unit. The x aesthetic runs along the spiral as the angle, y becomes the radius inside the track. Lines, bars, points and areas are supported, the matching angle and radial axes are drawn automatically, and facet_wrap() / facet_grid() get one spiral per panel.

set.seed(42)
d_sp <- data.frame(
  x = seq(0, 1, length.out = 300),
  y = sin(seq(0, 1, length.out = 300) * 8 * pi) * 0.35 + 0.5
)
ggplot(d_sp, aes(x, y)) +
  geom_line(colour = "#2166ac", linewidth = 0.6) +
  coord_spiral() +
  labs(x = NULL, y = NULL, title = "coord_spiral(): three turns")
coord_spiral(): a line on three turns, with the angle and radial axes

coord_spiral(): a line on three turns, with the angle and radial axes

The main arguments: start / end are degrees (360 * n + a means n turns ending at a); period sets how many x units one turn covers; height is the track height as a fraction of the gap between turns; scale_by = "angle" (default) maps equal x steps to equal angles, while "curve" maps them to equal lengths along the spiral. clockwise, reverse and flip control direction, labels = FALSE turns the axes off, and y_axis_theta chooses where the radial ruler is placed (the outer end by default).

d_sp$set <- rep(c("A", "B"), length.out = 300)
ggplot(d_sp, aes(x, y)) +
  geom_line() +
  facet_wrap(~set) +
  coord_spiral(end = 360 + 90) +
  labs(x = NULL, y = NULL, title = "Two panels, two spirals") +
  theme(plot.title = element_text(size = 11))
facet_wrap(): one spiral per panel, each with its own axis

facet_wrap(): one spiral per panel, each with its own axis

Spiral heat map: 300 genes x 8 samples

A heat map is the most typical use of the spiral: genes run along the spiral (x) and samples stack along the radius (y), with every geom_tile() cell bending with the track. This uses the package’s built-in data, the same matrix as the circular heat map above (GEO GSE52778, per-sample z-scores):

data(airway_heatmap)
d_hm <- airway_sample_z
d_hm$x <- as.numeric(d_hm$gene)
d_hm$y <- as.numeric(d_hm$sample)

ggplot(d_hm, aes(x, y, fill = z_sample)) +
  geom_tile() +
  scale_fill_gradient2(low = "#2166ac", mid = "#f7f7f7", high = "#b2182b",
                       limits = c(-2.5, 2.5), oob = scales::squish, name = "z (sample)") +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  coord_spiral(turns = 4, height = .9, inner = .12, labels = FALSE) +
  labs(x = NULL, y = NULL)
The built-in data as a spiral heat map: 300 genes over four turns, with the eight samples as concentric bands

The built-in data as a spiral heat map: 300 genes over four turns, with the eight samples as concentric bands

Three things matter:

ggplot(d_hm, aes(x, y, fill = z_sample)) +
  geom_tile() +
  scale_y_continuous(expand = c(0, 0), breaks = 1:8,
                     labels = paste0("S", 1:8)) +
  scale_x_continuous(expand = c(0, 0)) +
  coord_spiral(turns = 2, height = .85, inner = .1)

An arrow along the spiral (spiral_arrow() style)

spiralize’s spiral_arrow(0.2, 0.8) is just an x interval interpolated into a geom_path() along the track, plus an arrow head. geom_path() is essential: it connects the interpolated points in data order, so the line follows the spiral; geom_segment() only has two end points and would cut straight across the panel.

d_arrow <- data.frame(x = seq(0.2, 0.8, length.out = 900), y = 0.5)

ggplot(d_arrow, aes(x, y)) +
  geom_path(linewidth = 2.6, colour = "#e41a1c", lineend = "round",
            arrow = grid::arrow(length = unit(5.5, "mm"), type = "closed")) +
  scale_x_spiral_axis(breaks = seq(0.2, 0.8, by = 0.05),
                      minor_breaks = seq(0.2, 0.8, by = 0.0125),
                      label_size = 5) +
  scale_y_spiral_axis(show = FALSE) +
  coord_spiral(turns = 3, height = .78, inner = .06, outer = .46, y_axis = FALSE)
An arrow along the spiral from x = 0.2 to 0.8, with minor ticks between the labelled ones

An arrow along the spiral from x = 0.2 to 0.8, with minor ticks between the labelled ones

The numbers are not arbitrary: linewidth = 2.6 mm is about 60% of the track, so the red band sits inside it; minor_breaks every 0.0125 puts four small ticks between two labelled ones, the way spiralize draws major ticks with labels and minor ticks without. For the opposite direction use scale_x_reverse().

Which layers are supported

coord_spiral() is an ordinary ggproto Coord: all it does is map every point from the data scale to panel coordinates. So any layer that hands its x/y to the coordinate transform just works, with no extra setup.

Layer Status Notes
geom_point() / geom_jitter() works points land on the track
geom_line() / geom_step() works the line is bent along the spiral
geom_path() works connects in data order, so an unordered path loops back
geom_area() / geom_ribbon() works both bounds follow the spiral
geom_col() / geom_bar() works bars become wedges of the track
geom_histogram() / geom_density() works binning and density are fine
geom_smooth() works curve and confidence band both follow the spiral
geom_tile() works heat maps unroll along the spiral (below)
geom_boxplot() / geom_violin() works needs a discrete x
geom_text() / geom_label() works keep the font small, or the text spans turns
geom_errorbar() / geom_pointrange() / geom_linerange() works whiskers become short arcs on the track
geom_polygon() works vertices are mapped, edges are straight (see below)
geom_raster() falls back warns that it needs a linear coord and draws via geom_rect()
geom_segment() / geom_curve() works both ends are transformed, arrows (arrow =) included; the edge between them is straight, invisible over short spans
geom_rect() works all four corners are transformed, giving a quad that hugs the track
geom_hline() / geom_vline() / geom_abline() not supported an infinite line has no end points to transform, so it turns into a closed shape
geom_sf() / geom_map() not supported they need coord_sf() / their own coord
library(patchwork)

## the layer examples are the ones from the ggplot2 reference pages
sp <- function(p, title) {
  p + coord_spiral(turns = 3, labels = FALSE) +
    labs(x = NULL, y = NULL, title = title) +
    theme(plot.title = element_text(size = 9),
          axis.text = element_text(size = 5),
          legend.position = "none")
}

wrap_plots(
  sp(ggplot(mpg, aes(displ, hwy)) + geom_point(), "geom_point()"),
  sp(ggplot(economics, aes(date, unemploy)) + geom_line(), "geom_line()"),
  sp(ggplot(economics, aes(date, unemploy)) + geom_area(fill = "#9ecae1"), "geom_area()"),
  sp(ggplot(mpg, aes(class, hwy)) + geom_col(), "geom_col()"),
  sp(ggplot(mpg, aes(hwy)) + geom_histogram(binwidth = 2), "geom_histogram()"),
  sp(ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(), "geom_smooth()"),
  sp(ggplot(mpg, aes(class, hwy)) + geom_boxplot(), "geom_boxplot()"),
  sp(ggplot(faithfuld, aes(waiting, eruptions, fill = density)) +
       geom_tile(), "geom_tile()"),
  sp(ggplot(mpg[seq(1, 234, 12), ], aes(displ, hwy, label = cyl)) +
       geom_text(size = 2), "geom_text()"),
  ncol = 3
)
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
ggplot2's own layer examples drawn on coord_spiral(): points, line, area, bars, histogram, smooth, boxplot, heat map, text

ggplot2’s own layer examples drawn on coord_spiral(): points, line, area, bars, histogram, smooth, boxplot, heat map, text

Why the edges between two points are straight: the transform is applied to every position aesthetic (x, y, xend, yend, xmin, xmax, ymin, ymax), but the edge between two transformed points is still a straight segment. Over a short span you cannot see the difference - the figure below is a copy of spiralize::spiral_segments(), where every segment spans only 0.02 x units and looks like it lies exactly on the track. Over a long span the chord becomes visible; in that case draw the line with geom_path() instead, interpolating intermediate points along the arc and separating the pieces with group.

set.seed(2)
n <- 400
d_seg <- data.frame(
  x  = runif(n), y = runif(n)
)
d_seg$xend <- d_seg$x + runif(n, min = -0.01, max = 0.01)
d_seg$yend <- 1 - d_seg$y
d_seg$col <- grDevices::hcl.colors(n, "Dark 3")

p_seg <- ggplot(d_seg, aes(x, y)) +
  geom_segment(aes(xend = xend, yend = yend), colour = d_seg$col,
               linewidth = .6, show.legend = FALSE) +
  coord_spiral(turns = 4, height = .85, labels = FALSE)

p_arrow <- ggplot(d_seg[seq_len(120), ], aes(x, y)) +
  geom_segment(aes(xend = xend, yend = yend), colour = d_seg$col[seq_len(120)],
               linewidth = .6, show.legend = FALSE,
               arrow = arrow(length = unit(2, "mm"))) +
  coord_spiral(turns = 4, height = .85, labels = FALSE)

wrap_plots(p_seg, p_arrow, ncol = 2)
A copy of spiralize's Segments example: coloured segments on the left, segments with arrow heads on the right

A copy of spiralize’s Segments example: coloured segments on the left, segments with arrow heads on the right

Radial and stacked bars

The spiralize::spiral_bars() look comes straight out of geom_col(): bars grow from the smallest y (usually 0) towards the outside, and width sets how much of the angle they take. Setting expand to 0 makes the bars fill the track, with no gap before the first one or after the last one.

set.seed(1)

## one value per column
d1 <- data.frame(x = seq_len(240), v = runif(240, .05, 1))
p1 <- ggplot(d1, aes(x, v)) +
  geom_col(width = 1, fill = "grey20") +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  coord_spiral(turns = 3, height = .8) +
  labs(x = NULL, y = NULL, title = "one column: geom_col()")

## a matrix: one column per stack
n <- 200
m <- matrix(runif(3 * n), ncol = 3)
m <- m / rowSums(m)
d2 <- data.frame(x = rep(seq_len(n), 3),
                 stack = factor(rep(c("A", "B", "C"), each = n)),
                 v = as.vector(m))
p2 <- ggplot(d2, aes(x, v, fill = stack)) +
  geom_col(width = 1) +
  scale_fill_manual(values = c("#4C72B0", "#DD8452", "#55A868")) +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  coord_spiral(turns = 3, height = .8) +
  labs(x = NULL, y = NULL, title = "matrix columns: stacked")

wrap_plots(p1, p2, ncol = 2) &
  theme(plot.title = element_text(size = 10), legend.position = "bottom")
Left: one bar per column. Right: the same data stacked

Left: one bar per column. Right: the same data stacked

Stacking works because y is the radius inside the track: position = "stack" stacks the pieces along the radius, so every column of the matrix becomes one concentric band. In the same way position = "dodge" spreads the bars along the angle, and position = "fill" normalises them to the track width.

Cluster dendrogram on a discrete axis

guide_axis_cluster() adds a hierarchical clustering dendrogram to an x or y discrete axis; the companion scale_x_cluster() / scale_y_cluster() reorder the categories into dendrogram leaf order. The key point: the companion scale sets limits to the clustered order, so both the axis labels and the data in the plot are reordered together and the tree stays aligned with the data – there is no “labels changed but cells stayed put” mismatch.

set.seed(1)
mat <- matrix(rnorm(12 * 4), nrow = 12,
              dimnames = list(paste0("g", 1:12), paste0("s", 1:4)))
long <- as.data.frame(as.table(mat))
names(long) <- c("gene", "sample", "value")

A rectangular dendrogram on the y axis (type = "rectangle", the default); method selects the clustering method, height is the overall tree height in centimetres, and col sets the line colour:

ggplot(long, aes(sample, gene, fill = value)) +
  geom_tile() +
  scale_y_cluster(mat, method = "average", height = 1.4, col = "#2c7fb8") +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b", midpoint = 0) +
  theme_minimal(base_size = 11)
Rectangular cluster tree on the y axis; genes are reordered by clustering

Rectangular cluster tree on the y axis; genes are reordered by clustering

The triangular tree (type = "triangle") converges to a single vertex at every merge, drawn like plot(as.dendrogram(hc), type = "triangle"):

ggplot(long, aes(gene, sample, fill = value)) +
  geom_tile() +
  scale_x_cluster(mat, method = "ward.D2", height = 1.4,
                  col = "#b2182b", type = "triangle") +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b", midpoint = 0) +
  theme_minimal(base_size = 11)
Triangular cluster tree on the x axis

Triangular cluster tree on the x axis

method: a different linkage, a different tree

method goes straight to stats::hclust(). The two figures above use average and ward.D2; switch to "single" (nearest-neighbour chaining) and the tree collapses into a chain, with the leaves re-ordered as well:

ggplot(long, aes(sample, gene, fill = value)) +
  geom_tile() +
  scale_y_cluster(mat, method = "single", height = 1.4, col = "#7b3294") +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                       midpoint = 0) +
  theme_minimal(base_size = 11)
method = 'single': chaining gives a visibly different tree from average / ward.D2

method = ‘single’: chaining gives a visibly different tree from average / ward.D2

A tree on both axes

scale_x_cluster() clusters the columns, scale_y_cluster() the rows; the two trees stay out of each other’s way and both axes are re-ordered:

ggplot(long, aes(gene, sample, fill = value)) +
  geom_tile() +
  scale_x_cluster(position = "top", height = 1.1) +
  scale_y_cluster(position = "left", height = 1.1) +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                       midpoint = 0) +
  theme_minimal(base_size = 11)
x tree on top, y tree on the left: rows and columns both in cluster order

x tree on top, y tree on the left: rows and columns both in cluster order

To get just the clustered order without the companion scale, use cluster_order(), e.g. scale_y_discrete(limits = cluster_order(mat)).

position: move the tree, not the labels

position decides which side the tree is drawn on; the labels never move:

axis position tree labels
x "bottom" (default) outside the labels, by the gene title still at the bottom
x "top" above the panel; with facets, under the strip still at the bottom
y "left" (default) left of the labels still on the left
y "right" at the end of the panel row still on the left
tile_x <- function(pos) {
  ggplot(long, aes(gene, sample, fill = value)) +
    geom_tile() +
    scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                         midpoint = 0) +
    scale_x_cluster(position = pos, height = 1) +
    theme_minimal(base_size = 11)
}
tile_y <- function(pos) {
  ggplot(long, aes(sample, gene, fill = value)) +
    geom_tile() +
    scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                         midpoint = 0) +
    scale_y_cluster(position = pos, height = 1) +
    theme_minimal(base_size = 11)
}

x tree on top, labels still at the bottom:

tile_x("top")
position = 'top': tree above the panel, x labels stay at the bottom

position = ‘top’: tree above the panel, x labels stay at the bottom

y tree on the left, left of the labels:

tile_y("left")
position = 'left': tree left of the y labels

position = ‘left’: tree left of the y labels

y tree on the right, at the end of the panel row:

tile_y("right")
position = 'right': tree to the right of the panel

position = ‘right’: tree to the right of the panel

The tree can leave the labels because it no longer goes through a secondary axis: it is drawn straight into the final gtable, the only place that knows the geometry of every panel. That is also why facet_grid() works – row facets own the y axis and column facets own the x axis, so each tree lands under its own strip.

No matrix needed

None of the examples above pass a matrix: scale_x_cluster() / scale_y_cluster() derive it at draw time from the plot’s own data – the focal axis becomes the rows, the other positional axis the columns, and the first numeric aesthetic (fill, colour, size, …) the value. To cluster on another column, say value =:

ggplot(d, aes(gene, sample, fill = zscore, size = pct)) +
  geom_point() +
  scale_x_cluster(value = "zscore")   # defaults to the first numeric aesthetic

Changing value = changes the tree as well. The dot plot below carries both fill (expression) and size (fraction expressed); clustering on one or the other gives different trees:

set.seed(7)
d_val <- expand.grid(gene = paste0("g", 1:12), sample = paste0("s", 1:6))
d_val$zscore <- stats::rnorm(nrow(d_val))
d_val$pct <- stats::runif(nrow(d_val), 0, 1)
p_val <- function(v) {
  ggplot(d_val, aes(gene, sample, fill = zscore, size = pct)) +
    geom_point(shape = 21, colour = "grey25") +
    scale_x_cluster(value = v, height = 1.1) +
    scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b") +
    labs(title = paste0("value = \"", v, "\"")) +
    theme_bw(base_size = 10)
}
wrap_plots(p_val("zscore"), p_val("pct"), nrow = 1)
One dot plot, clustered on fill (left) and on size (right): the trees differ

One dot plot, clustered on fill (left) and on size (right): the trees differ

Facets: one tree per panel

A single-cell dot plot is usually faceted by cell type, and every panel holds a different gene set. Hand scales to the facet and the tree is recomputed per panel automatically – no free = TRUE needed:

data(pbmc3k_dotplot)
d4 <- droplevels(pbmc3k_dotplot[pbmc3k_dotplot$celltype %in%
                                  c("Naive CD4 T", "CD14+ Mono", "NK", "B"), ])
d4$cluster_id <- factor(d4$cluster_id)      # cluster id on y: 0 / 1 / 3 / 6
top_of <- function(x, k) head(x$gene[order(-x$avg_exp_scaled)], k)

dot_layers <- function() {
  list(
    geom_point(aes(size = pct_expressed, fill = avg_exp_scaled),
               shape = 21, colour = "black", stroke = 0.25),
    scale_fill_gradient2(low = "#2166ac", mid = "#f7f7f7", high = "#b2182b"),
    theme_bw(base_size = 10),
    theme(axis.text.x = element_text(angle = 45, hjust = 1),
          panel.grid.minor = element_blank())
  )
}

genes_by_ct <- lapply(split(d4, d4$celltype), top_of, k = 4)
d_panel <- do.call(rbind, lapply(names(genes_by_ct), function(ct) {
  x <- d4[d4$gene %in% genes_by_ct[[ct]], ]
  x$panel <- ct
  x
}))
d_panel$panel <- factor(d_panel$panel, levels = names(genes_by_ct))
ggplot(d_panel, aes(gene, cluster_id)) + dot_layers() +
  facet_wrap(~ panel, scales = "free_x") +
  scale_x_cluster(position = "top", height = 0.9) +
  theme(aspect.ratio = 1)
facet_wrap(scales = 'free_x'): one x tree per panel, tucked under its own strip

facet_wrap(scales = ‘free_x’): one x tree per panel, tucked under its own strip

The four scales modes: when the tree is recomputed

facet_wrap() / facet_grid() scales are picked up automatically; whether the tree is recomputed per panel depends only on whether that axis is free:

scales x axis y axis x tree y tree
"fixed" shared shared one tree for all panels one per axis
"free_x" per panel shared one per panel column one per axis
"free_y" shared per panel one tree for all panels one per panel row
"free" per panel per panel one per panel column one per panel row
sets <- list("All four" = c("Naive CD4 T", "CD14+ Mono", "NK", "B"),
             "T + Mono" = c("Naive CD4 T", "CD14+ Mono"),
             "NK + B"   = c("NK", "B"))
d_xy <- do.call(rbind, lapply(names(sets), function(p) {
  x <- d4[d4$celltype %in% sets[[p]] & d4$gene %in% genes_by_ct[[sets[[p]][1]]], ]
  x$panel <- p
  x
}))
d_xy$panel <- factor(d_xy$panel, levels = names(sets))

By default the tree is inserted between the strip and the panel, with a small gap to the strip (options(ggutils.tree_gap = 0.14), centimetres). Add strip_side to move it outside the strip instead:

scale_x_cluster(position = "top", strip_side = "above")
ggplot(d_xy, aes(gene, cluster_id)) + dot_layers() +
  facet_wrap(~ panel, nrow = 1, scales = "free_x") +
  scale_x_cluster(position = "top", height = 0.9, strip_side = "above") +
  theme(aspect.ratio = 1)
strip_side = 'above': the tree moves outside the strip, which stays flush with the panel

strip_side = ‘above’: the tree moves outside the strip, which stays flush with the panel

free_x: each panel has its own gene set, so each x tree is computed on its own, while the y axis stays shared:

ggplot(d_xy, aes(gene, cluster_id)) + dot_layers() +
  facet_wrap(~ panel, scales = "free_x") +
  scale_x_cluster(position = "top", height = 0.9)
scales = 'free_x': per-panel x trees

scales = ‘free_x’: per-panel x trees

free_y: x shared, y per panel, and the y tree becomes one per panel as well, hugging its own cluster labels:

ggplot(d_xy, aes(gene, cluster_id)) + dot_layers() +
  facet_wrap(~ panel, scales = "free_y") +
  scale_x_cluster(position = "top", height = 0.9) +
  scale_y_cluster(position = "left", height = 0.9)
scales = 'free_y': shared x tree, per-panel y trees

scales = ‘free_y’: shared x tree, per-panel y trees

Freeing both directions and adding a y tree squeezes the panels very thin; usually keep one direction. See the acceptance report in the package for the full comparison.

Multi-row facets: each row owns its own strip

With nrow = 2 the trees are inserted row by row, so the second row’s trees never bleed into the first:

## four panels of two cell types each (= two clusters), same size, to show the layout
sets2 <- list("T + Mono"  = c("Naive CD4 T", "CD14+ Mono"),
              "NK + B"    = c("NK", "B"),
              "Mono + B"  = c("CD14+ Mono", "B"),
              "T + NK"    = c("Naive CD4 T", "NK"))
d_grid <- do.call(rbind, lapply(names(sets2), function(p) {
  x <- d4[d4$celltype %in% sets2[[p]] & d4$gene %in% genes_by_ct[[sets2[[p]][1]]], ]
  x$panel <- p
  x
}))
d_grid$panel <- factor(d_grid$panel, levels = names(sets2))
ggplot(d_grid, aes(gene, cluster_id)) + dot_layers() +
  facet_wrap(~ panel, scales = "free", nrow = 2) +
  scale_x_cluster(position = "top", height = 0.8)
facet_wrap(nrow = 2): the 4 x trees land under their own panel's strip

facet_wrap(nrow = 2): the 4 x trees land under their own panel’s strip

facet_grid(): rows own y, columns own x

In facet_grid() the row facet decides y and the column facet decides x, so the x tree sits under the column strip and the y tree on the left of each row. Add two categorical columns and build a 2x2: grp splits the clusters in two (rows) and prog splits the genes into two marker sets (columns):

prog_a <- unique(unlist(lapply(c("Naive CD4 T", "CD14+ Mono"),
                               function(ct) top_of(d4[d4$celltype == ct, ], 3))))
prog_b <- unique(unlist(lapply(c("NK", "B"),
                               function(ct) top_of(d4[d4$celltype == ct, ], 3))))
d_fg <- d4[d4$gene %in% c(prog_a, prog_b), ]
d_fg$grp <- factor(ifelse(as.character(d_fg$cluster_id) %in% c("0", "1"),
                          "c0 / c1", "c3 / c6"), levels = c("c0 / c1", "c3 / c6"))
d_fg$prog <- factor(ifelse(d_fg$gene %in% prog_a, "T / Mono", "NK / B"),
                    levels = c("T / Mono", "NK / B"))
ggplot(d_fg, aes(gene, cluster_id)) + dot_layers() +
  facet_grid(grp ~ prog, scales = "fixed", drop = FALSE) +
  scale_x_cluster(position = "top", height = 0.8) +
  scale_y_cluster(position = "left", height = 0.8)
facet_grid(grp ~ prog): x tree under the column strip, y tree left of each row

facet_grid(grp ~ prog): x tree under the column strip, y tree left of each row

Two things to keep in mind: drop = FALSE is there to make fixed visible – a discrete y axis drops empty levels per panel by default, and once it does, fixed and free_y look identical; without dropping, fixed tiles all clusters into every panel. And the number of y trees does not change with free inside facet_grid(), because the row itself is the y facet, so every row always has one y axis – fixed vs free_y only changes how many leaves a tree has.

An RNA-seq heatmap: faceted by gene set, one y tree per panel

Real RNA-seq heatmaps are usually split by gene set (up / down), and each facet holds entirely different genes – the textbook case for per-panel trees. The bundled airway_heatmap (dexamethasone-treated human airway smooth muscle cells, 300 variable genes x 8 samples) is used below. The data already carries a The bundled matrix is a per-gene row z-score; below every sample is standardised again across the 300 genes (scale() works column-wise), giving z_sample, so fill = z_sample with scale_fill_gradient2(midpoint = 0) draws the standard red/blue heatmap.

Below: the 18 strongest genes of each set, faceted by gene_set with scales = "free_y" so every panel lays out only its own genes – and therefore gets its own y tree. The sample axis gets one x tree, which clusters the treatment and control samples into two branches:

data(airway_heatmap, package = "ggutils")
gs <- airway_heatmap$genes
top_set <- do.call(rbind, lapply(split(gs, gs$gene_set), function(d) {
  head(d[order(-abs(d$delta)), ], 18)
}))
d_hm <- droplevels(airway_sample_z[airway_sample_z$gene %in% top_set$gene, ])
ggplot(d_hm, aes(sample, gene, fill = z_sample)) +
  geom_tile() +
  facet_wrap(~ gene_set, scales = "free_y", nrow = 1) +
  scale_x_cluster(position = "top", height = 0.8, col = "grey25") +
  scale_y_cluster(position = "left", height = 1.2, col = "grey25") +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                       midpoint = 0, name = "z-score (sample)") +
  theme_bw(base_size = 9) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1),
        panel.grid = element_blank())
Airway heatmap faceted by gene set: one y tree per panel plus a sample x tree on top

Airway heatmap faceted by gene set: one y tree per panel plus a sample x tree on top

With fixed the two panels share one gene axis and each wastes a large empty block; free_y plus a per-panel tree is what this “different genes per facet” data asks for. The x axis is shared, so the sample tree is drawn once and lines up with both panels.

Radial coordinates: ring trees on the theta axis, arc tree on the r axis

Around a circle there is no “row above the panel” to put a tree in, so on a coord_radial() theta axis scale_x_cluster() draws a ring dendrogram: leaves sit on a ring, every merge is an arc at another radius joined to its children by radial stubs (type = "triangle" uses straight chords to the merge point instead). The labels keep their normal guide_axis_theta() look.

position decides which side the ring tree goes to:

position tree drawn notes
"bottom" (default) inside the hole leaves on the inner circle, merges towards the centre; needs inner.radius > 0, a pie without a hole is skipped
"top" outside the circle leaves on the outer circle, merges outwards; ring_gap is measured from the labels and the panel is padded automatically

Ring tree inside the hole (a donut heat map):

data(airway_heatmap, package = "ggutils")
d_ring <- droplevels(
  airway_sample_z[airway_sample_z$gene %in% unique(airway_sample_z$gene)[1:30], ]
)
ggplot(d_ring, aes(gene, sample, fill = z_sample)) +
  geom_tile() +
  coord_radial(theta = "x", inner.radius = 0.55) +
  scale_x_cluster(method = "ward.D2", height = 1.1) +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                       midpoint = 0, name = "z-score (sample)") +
  theme_grey(base_size = 8) +
  theme(plot.margin = margin(0.6, 0.6, 0.6, 0.6, "cm"),
        legend.position = "bottom") +
  labs(x = NULL, y = NULL)
coord_radial(inner.radius = 0.55) + position = 'bottom': tree inside the hole, merges towards the centre

coord_radial(inner.radius = 0.55) + position = ‘bottom’: tree inside the hole, merges towards the centre

position = "top" puts the same tree outside the circle; the leaf ring starts after the labels and the panel gets extra room automatically:

ggplot(d_ring, aes(gene, sample, fill = z_sample)) +
  geom_tile() +
  coord_radial(theta = "x") +
  scale_x_cluster(method = "ward.D2", height = 1, position = "top") +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                       midpoint = 0, name = "z-score (sample)") +
  theme_grey(base_size = 8) +
  theme(plot.margin = margin(0.8, 0.8, 0.8, 0.8, "cm"),
        legend.position = "bottom") +
  labs(x = NULL, y = NULL)
coord_radial() + position = 'top': tree outside the circle, merges outwards

coord_radial() + position = ‘top’: tree outside the circle, merges outwards

Facets work like the cartesian ones – one tree per panel, clustered from that panel’s own genes when the theta scale is free (free_x / free):

d_ring2 <- droplevels(
  airway_sample_z[airway_sample_z$gene %in% unique(airway_sample_z$gene)[1:60], ]
)
ggplot(d_ring2, aes(gene, sample, fill = z_sample)) +
  geom_tile() +
  facet_wrap(~ gene_set, scales = "free_x") +
  coord_radial(theta = "x", inner.radius = 0.45) +
  scale_x_cluster(method = "ward.D2", height = 0.8) +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                       midpoint = 0, name = "z-score (sample)") +
  theme_grey(base_size = 7) +
  theme(plot.margin = margin(0.4, 0.4, 0.4, 0.4, "cm"),
        legend.position = "bottom") +
  labs(x = NULL, y = NULL)
facet_wrap(scales = 'free_x') + coord_radial: one inner ring tree per panel

facet_wrap(scales = ‘free_x’) + coord_radial: one inner ring tree per panel

Arc tree on the r (y) axis

On a full circle the r axis is just a column of labels, so scale_y_cluster() draws no tree there. With a partial arc (start / end) ggplot2 puts the sample labels on a radial ray, and scale_y_cluster() then draws an arc-shaped wedge tree at the other end of the arc – the side without labels:

  • leaf position -> radius: every sample lines up with its own ring;
  • merge height -> angle: height sets the angular width (min(pi/3, 0.30 * height) radians);
  • equal-height branches are concentric arcs and the leaf stubs hug the tiles, so the whole tree is made of arcs.
d_ring_y <- droplevels(
  airway_sample_z[airway_sample_z$gene %in% unique(airway_sample_z$gene)[1:16], ]
)
ggplot(d_ring_y, aes(gene, sample, fill = z_sample)) +
  geom_tile() +
  coord_radial(theta = "x", start = -0.5 * pi, end = 0.5 * pi,
               inner.radius = 0.55) +
  scale_y_cluster(method = "ward.D2", height = 1.6) +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                       midpoint = 0, name = "z-score (sample)") +
  theme_grey(base_size = 8) +
  theme(plot.margin = margin(0.6, 0.6, 0.6, 0.6, "cm"),
        legend.position = "bottom") +
  labs(x = NULL, y = NULL)
180 degree arc + scale_y_cluster(): arc tree at the label-free end of the arc

180 degree arc + scale_y_cluster(): arc tree at the label-free end of the arc

90/270 degree arcs work the same way, only start / end change, and the r-axis tree can be combined with an x tree on the same plot.

Facet scales: the trees follow the facet

The previous sections all used facet_wrap(). Switching to facet_grid() or facet_gridn() needs no free = TRUE: scale_*_cluster() reads the facet’s scales directly, and whether the tree is per panel depends only on whether that axis is free (the six scales values of both facets are tabulated in “facet_gridn(): a per-panel facet_grid” above).

facet_gridn(scales = "free_x") is per panel, so every cell gets its own x tree:

ggplot(d_xy, aes(gene, cluster_id)) + dot_layers() +
  facet_gridn(cols = vars(panel), scales = "free_x") +
  scale_x_cluster(position = "top", height = 0.9) +
  theme(aspect.ratio = 1)
facet_gridn(scales = 'free_x'): every panel gets its own x axis and its own x tree

facet_gridn(scales = ‘free_x’): every panel gets its own x axis and its own x tree

Switch to scales = "free" and add scale_y_cluster() to get one x tree and one y tree per cell:

ggplot(d_xy, aes(gene, cluster_id)) + dot_layers() +
  facet_gridn(cols = vars(panel), scales = "free") +
  scale_x_cluster(position = "top", height = 0.9) +
  scale_y_cluster(position = "left", height = 0.9) +
  theme(aspect.ratio = 1)
facet_gridn(scales = 'free'): per-panel x and y trees

facet_gridn(scales = ‘free’): per-panel x and y trees

Limits of the cluster tree

Known limitations and tuning advice

Session info

cat("ggplot2:", as.character(packageVersion("ggplot2")), "\n")
#> ggplot2: 4.0.3
cat("ggutils:", as.character(packageVersion("ggutils")), "\n")
#> ggutils: 0.0.3
cat("R:", R.version.string, "\n")
#> R: R version 4.5.1 (2025-06-13 ucrt)