ggplot2 facet_grid custom labeller with group, sub

2019-07-17 21:45发布

问题:

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

For (1), using expression(), I can only get it to 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 the value, using paste() works for rather simple math expr, only. For example:

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 function "group"). Even without group() it does not work: "A['i,j']" is then displayed "as is", i.e., 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, either:

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

Printing the bquoted expression with text() works, though.

回答1:

I'm sure there's a simpler and better way, but here's an 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)


标签: r ggplot2