Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facet_Wrap labels in R

I'm trying to change labels for ggplot graph with facets, and am using a variable from the dataframe which is not faceted. The code is as belows-

iris %>%
  group_by(Species) %>%
  summarise(lbl = mean(Petal.Length)) %>%
  select(lbl) %>%
  unlist() -> lbls
lbls <- map2(unique(iris$Species), lbls, paste, sep = "\n")
iris %>%
  ggplot(aes(x = Sepal.Length, y = Sepal.Width, group = 1)) +
  geom_point() +
  facet_wrap(~ Species, labeller = lbls)

However, this gives me the following error-

Error in cbind(labels = list(), list(`{`, if (!is.null(.rows) || 
!is.null(.cols)) { : 
 number of rows of matrices must match (see arg 2)

I've looked at the labeller function and different options but most of them seem to be for variables which are included in facets. Is there a way this can be done? Any leads appreciated, thanks!

like image 223
Mridul Garg Avatar asked Mar 26 '18 16:03

Mridul Garg


2 Answers

From the documentation on ?labeller, labeller can also be a named character vector. Note that we need to wrap the character vector in the labeller function. Also from looking at the examples in the help file, we need to pass the facetting variable Species as the argument to labeller. Thus the call should look something like:

labeller = labeller(Species = setNames(unlist(lbls), unique(iris$Species)))

The code should then be:

iris %>%
  ggplot(aes(x = Sepal.Length, y = Sepal.Width, group = 1)) +
  geom_point() +
  facet_wrap(~ Species, labeller = labeller(Species = setNames(unlist(lbls), unique(iris$Species))))

Also, a much cleaner way to create the labels would be without map2:

lbls <- setNames(paste(unique(iris$Species), lbls, sep = "\n"), unique(iris$Species))

enter image description here

like image 53
Mike H. Avatar answered Sep 30 '22 04:09

Mike H.


You could create a new facetting column on the fly and avoid labeller pain:

iris %>%
  group_by(Species) %>% 
  mutate(label = paste0(Species, "\n", round(mean(Petal.Length),2))) %>% 
  ggplot(aes(x = Sepal.Length, y = Sepal.Width, group = 1)) +
    geom_point() +
    facet_wrap(~ label)

enter image description here

like image 35
eipi10 Avatar answered Sep 30 '22 05:09

eipi10