How can I paste an additional constant text to ggplot facet labels?
For example, I have this current plot:
library(ggplot2)
df <- data.frame(
x = rnorm(120, c(0, 2, 4)),
y = rnorm(120, c(1, 2, 1)),
z = letters[1:3]
)
ggplot(df, aes(x, y)) +
geom_point() +
facet_wrap(~z)
Created on 2024-05-05 with reprex v2.0.2
Now let’s say that I want to add the same prefix (Foo = ) string to all facet labels:
If I do
ggplot(df, aes(x, y)) +
geom_point() +
facet_wrap(~z, labeller = \(x) paste("foo = ", x))
I get:
How can I tweak the function I pass to labeller to show foo = [preexisting label] ?
>Solution :
You have to wrap your function inside labeller() like so:
library(ggplot2)
set.seed(123)
df <- data.frame(
x = rnorm(120, c(0, 2, 4)),
y = rnorm(120, c(1, 2, 1)),
z = letters[1:3]
)
ggplot(df, aes(x, y)) +
geom_point() +
facet_wrap(~z,
labeller = labeller(z = \(x) paste("foo = ", x))
)


