1

Suppose I have the following dataset:

set.seed(1212)
a = sample(c("A", "B"), size=100, replace=T)
x = rnorm(100)
y = model.matrix(~a + x) %*% c(0, .5, .5) + rnorm(100, 0)
d = data.frame(a=a, x=x, y=y)

I can easily produce a ggplot that panels the variable a:

p = ggplot(d, aes(x=x, y=y)) + 
  geom_point() + 
  geom_smooth(method="lm") +
  facet_grid(~a, labeller=label_both)
p

ggplot without custom labels

I can also easily modify the labels for X/Y:

p + labs(x="My X Label", y="My Y Label")

ggplot with custom labels on x/y

But I don't know how to easily change the labels for the strip. None of these work:

p + labs(x="My X Label", y="My Y Label", strip = "A")
p + labs(x="My X Label", y="My Y Label", grid = "A")
p + labs(x="My X Label", y="My Y Label", panel = "A")
p + labs(x="My X Label", y="My Y Label", wtf = "A")

I know that I can just change my variable name:

ggplot(d %>% rename(`A Fancy Label` = a),
       aes(x=x,y=y)) +
  geom_point() +
  geom_smooth() + 
  facet_grid(~`A Fancy Label`, labeller=label_both)

Or I could use some sort of custom labeller. But, I'm producing ggplot graphics within my R package, and the labeller is built into the R package and cannot be easily modified.

So, now to my question: how do I change the variable label of the facets in a way that doesn't require me to modify the actual variable or to use some custom labeller function?

After much googling, I can only find how to change the value labels of the facets, not the variable labels of the facets (e.g., this question/answer).

Thanks in advance!

dfife
  • 348
  • 1
  • 12
  • Does the global_labeller() function defined here help at all? https://ggplot2.tidyverse.org/reference/labeller.html – joncgoodwin Oct 27 '21 at 12:11
  • It's not optimal. I'd much rather change the label post-plot (as you would with layering), rather than changing the function that produces the plot. – dfife Oct 27 '21 at 14:25

1 Answers1

1

This may not be the perfect one. But, you can have the same label over the facet labels by adding "Fancy Label" to the facet_grid function.

p = ggplot(d, aes(x=x, y=y)) + 
  geom_point() + 
  geom_smooth(method="lm") +
  facet_grid(~ "Fancy Label" + a)  
  
p  + labs(x="My X Label", y="My Y Label")

enter image description here

Mohanasundaram
  • 2,889
  • 1
  • 8
  • 18
  • Thanks for the suggestion, and I may have to resort to that. I'd much rather modify the plot after it's already produced so I don't have to tinker with my plot function's internal workings (i.e., the flexplot function). That would require adding another argument to the function, which I'm trying to minimize since the function already has 20+ arguments. – dfife Oct 27 '21 at 14:27