Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

r - Adding expressions to facet labeller in ggplot 2 2.0

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...