rnorouzian
rnorouzian

Reputation: 7517

changing the facet_wrap labels using labeller in ggplot2

In my ggplot below, I'm trying to change the 10 facet labels of facet_wrap using labeller(sch.id=paste0("sch.id:", unique(ten$sch.id))).

However, the plot shows NA instead of the correct facet labels, I wonder what the fix is?

library(ggplot2)

hsb <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/hsb.csv')

ten <- subset(hsb, sch.id %in% unique(sch.id)[1:10])

p <- ten %>% ggplot() + aes(ses, math) + geom_point() +
 facet_wrap(~sch.id) + geom_smooth(method = "lm", se = FALSE)

p + facet_wrap(~sch.id, labeller = labeller(sch.id=paste0("sch.id:", unique(ten$sch.id)))) ## HERE ##

Upvotes: 5

Views: 7121

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389047

I think the easiest way would be to change sch.id before plotting.

library(ggplot2)
ten$sch.id <- paste0("sch.id:", ten$sch.id)

ggplot(ten) + aes(ses, math) + 
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) + 
  facet_wrap(~sch.id)

enter image description here


If you don't want to modify your data and want to use the labeller argument you can create a named vector and use it in labeller.

cust_label <- setNames(paste0("sch.id:", unique(ten$sch.id)), unique(ten$sch.id))

ggplot(ten) + aes(ses, math) + 
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) + 
  facet_wrap(~sch.id, labeller = as_labeller(cust_label))

Upvotes: 2

Rui Barradas
Rui Barradas

Reputation: 76460

The problem seems to be that you are passing a variable to the labeller function but facet_wrap already passes its own faceting variable. A conflict occurs and the result are NA's.
The solution is to create a labeller function as a function of a variable x (or any other name as long as it's not the faceting variables' names) and then coerce to labeller with as_labeller.

Note that there is no need for unique, just like there is no need for it in the facet_wrap formula.

p <- ten %>% ggplot() + aes(ses, math) + geom_point() +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE)

cust_labeller <- function(x) paste0("sch.id:", x)
p + facet_wrap(~ sch.id, 
               labeller = as_labeller(cust_labeller)) ## HERE ##

enter image description here

Upvotes: 6

Related Questions