dfife
dfife

Reputation: 358

Modify facet (strip) *variable* labels in ggplot

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!

Upvotes: 2

Views: 2142

Answers (1)

Mohanasundaram
Mohanasundaram

Reputation: 2949

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

Upvotes: 1

Related Questions