I'm trying to make a ggplot where the labels have...
^a
This turns out to be pretty complicated. We need plotmath (or something else...) in order to make the exponents work. But the usual ways of making linebreaks (i.e. atop()
) only does one linebreak. (I think there might be away with expression()
and bquote()
but could not figure this out in a ggplot context.)
This does need to be ggplot and not base R. I'm applying this to a number of plots that are already carefully designed in ggplot and I don't have time to redo them in base R.
I'm trying to do something like the following (from this question) though of course the data won't look quite like this.
Here's what is mostly working...
my_data <- tribble(
~x, ~y, ~facet_var_basic, ~facet_var_expression, # Note: facet_var_expression doesn't work...
1, 1, "line a \n line b \n line c x^2", expression("line a \n line b \n line c x"^2),
2, 3, "line d \n line e \n line f x^2", expression("line d \n line e \n line f x"^2),
1, 3, "line g \n line h \n line i x^2", expression("line g \n line h \n line i x"^2)
)
# Set layout: 1 row, 3 columns (mfcol fills columns first)
par(mfcol=c(1,3),
mar=c(4,4,3,1), # smaller inner margins: bottom, left, top, right
oma=c(0,0,0,0)) # no outer margins
plot(1,1, main=my_data$facet_var_basic[1])
plot(2,3, main=my_data$facet_var_basic[2])
plot(1,3, main=my_data$facet_var_basic[3])
Unfortunately, the various iterations of the following which I have tried don't work...
my_data %>%
ggplot(aes(x = x, y = y)) +
geom_point() +
facet_wrap( ~ facet_var_basic)
The critical thing is to have (a) more than one linebreak and (b) this exponent at the end.
The easiest way is to use {ggtext}
and html labels. It seems that you are creating these labels manually, but if you have the facet_var_basic
column, then we can use some regex
to get facet_var_html
. I have added some more formatting variations to showcase what can be achieved using this solution.
library(ggplot2)
library(tibble)
library(ggtext)
my_data_html <- tribble(
~x, ~y, ~facet_var,
1, 1, "<b>Line a</b><br>Line b<br>Line c x<sup>2</sup>",
2, 3, "Line d<br><i>Line e</i><br>Line f y<sup>α</sup>",
1, 3, "Line g<br>Line h<br><i>
<b style='color: red'>Line i z<sub>β</sub></b></i>"
)
ggplot(my_data_html, aes(x = x, y = y)) +
geom_point(size = 3) +
facet_wrap(~ facet_var) +
theme(strip.text = element_markdown(size = 10, lineheight = 1.2))
Created on 2025-06-30 with reprex v2.1.1