Ggplot2 facet_grid user label with group, index and value

In conclusion, my question is how to create labels for facet_grid using (1) group("|",A['i,j'],"|") and (2) value ?

For (1), using expression() , I can make it work without value :

 plot_labeller <- function(variable,value){ print(value) if (variable=='FOO') { expr1 <- expression(group("|",A['i,j'],"|")) return(expr1) } else { return("bla") } } 

For (2), displaying value , using paste() only works for fairly simple math expr. For instance:

 plot_labeller <- function(variable,value){ if (variable=='FOO') { expr1 <- paste("alpha"," : ",value) return(expr1) } else { return("bar") } } 

However, paste() does not work with group() (e: could not find the function "group"). Even without group() it does not work: "A ['i, j']" is displayed "as is", that is, without applying plotmath . Using bquote() , as in:

 plot_labeller <- function(variable,value){ if (variable=='FOO') { expr1 <- bquote(group("|",A['i,j'],"|") : .(value)) return(expr1) } else { return("bar") } } 

does not work:

 Error in labels[, i] <- labeller(names(label_df)[i], label_df[, i]) : number of items to replace is not a multiple of replacement length 

However, printing the bquoted expression with text() works.

+2
source share
1 answer

I'm sure there is an easier and better way, but here is the idea:

 library(ggplot2) d <- data.frame(x=1:10, y=1:10, f=gl(2,5, labels=c("FOO","BLAH"))) make_label <- function(value) bquote(group("|",A['i,j'],"|"):.(value)) plot_labeller <- function(variable,value){ print(value) if(variable=='f') do.call(expression, lapply(levels(value)[value], make_label)) else "other" } qplot(x,y,data=d) + facet_grid(.~f, labeller=plot_labeller) 
+2
source

All Articles