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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With