Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding expressions to facet labeller in ggplot 2 2.0

Tags:

r

ggplot2

I need to replace one facet wrap label with a complicated expression. However, i cannot get the function facet_wrap_labeller to work anymore with plots created under older ggplot2 versions.

        data <- as.data.frame(matrix(rnorm(60),20,3)) 
        data$factor <- c(rep("f1", 4),rep("f2", 4), rep("f3", 4), rep("f4",4),rep("f5", 4))
        names(data) <- c("A", "B", "C", "factor")
        melted <- melt(data)

        p <- ggplot(melted, aes(variable, value)) +
             stat_boxplot(geom ='errorbar') + 
             geom_boxplot()
        p1 <- p + facet_wrap(~factor)
        facet_wrap_labeller(p1, labels=c("A", "B", expression({}^2*italic(D)~textstyle(group("(", rarefied, ")")))))

and i get:

Error in getGrob(gg[[strips[ii]]], "strip.text", grep = TRUE, global = TRUE) : 
  it is only valid to get a child from a "gTree"
Called from: getGrob(gg[[strips[ii]]], "strip.text", grep = TRUE, global = TRUE)

I believe this is happening because of ggplot2 2.0 not being compatible to this function.

I also tried the labeller=labeller(), and labeller=bquote() arguments, but when i tried to use this vector

newlabels <- c(A="A", B="B",,
    D=expression({}^0*italic(D)~textstyle(group("(", rarefied, ")"))))

in

p1 <- p + facet_wrap(~factor, 
           labeller = labeller(factor=newlabels))

the expression is ignored and the original factor levels are plotted. With bquote, i dont know to add more than one name to the argument.

Any help is appreciated.

like image 922
nouse Avatar asked Jan 24 '16 18:01

nouse


1 Answers

There only appear to be 4 labels for 5 facets in your example, but you could use labeller=label_parsed and rename the factor levels fairly easily, avoiding the need for another function.

## Rename levels (I used data.table::melt, so they were characters)
melted$factor <- factor(melted$factor, 
                        levels=paste0('f', 1:5),
                        labels=c('A', 'B', 'C', '{}^0*italic(D)~plain((rarefied))', 'E'))

p <- ggplot(melted, aes(variable, value)) +
  stat_boxplot(geom ='errorbar') + 
  geom_boxplot()
p + facet_wrap(~factor, labeller=label_parsed)

enter image description here

like image 76
Rorschach Avatar answered Sep 18 '22 22:09

Rorschach