Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add expressions to labels in facet_wrap? [duplicate]

Tags:

r

ggplot2

I have a dataset from which I would like to plot small multiples, specifically in a 2-by-2 array, like this:

mydf <- data.frame(letter = factor(rep(c("A", "B", "C", "D"), each = 20)), x = rnorm(80), y = rnorm(80))
ggplot(mydf, aes(x = x, y = y)) + geom_smooth(method = "lm") + geom_point() + facet_wrap(~ letter, ncol = 2)

However, I want each facet label to include an expression, such as

expression(paste("A or ", alpha))

I can make this happen using facet_grid() via

f_names <- list('A' = expression(paste("A or ", alpha)), 'B' = expression(paste("B or ", beta)), 'C' = expression(paste("C or ", gamma)), 'D' = expression(paste("D or ", delta)))
f_labeller <- function(variable, value){return(f_names[value])}
ggplot(mydf, aes(x = x, y = y)) + geom_smooth(method = "lm") + geom_point() + facet_grid(~ letter, labeller = f_labeller)

But then I lose the 2-by-2 array. How can I rename the facet_wrap() facet labels with an expression? Or, how can I solve this by recreating the 2-by-2 array using facet_grid(), but only faceting by a single variable?

(This question builds off of the parenthetical note in @baptiste's answer to this previous question.)

Thanks!

like image 600
RTM Avatar asked Oct 09 '13 21:10

RTM


1 Answers

In order to do what I asked, first load this labeller function from @Roland first appearing here:

facet_wrap_labeller <- function(gg.plot,labels=NULL) {
  #works with R 3.0.1 and ggplot2 0.9.3.1
  require(gridExtra)

  g <- ggplotGrob(gg.plot)
  gg <- g$grobs      
  strips <- grep("strip_t", names(gg))

  for(ii in seq_along(labels))  {
    modgrob <- getGrob(gg[[strips[ii]]], "strip.text", 
                       grep=TRUE, global=TRUE)
    gg[[strips[ii]]]$children[[modgrob$name]] <- editGrob(modgrob,label=labels[ii])
  }

  g$grobs <- gg
  class(g) = c("arrange", "ggplot",class(g)) 
  g
}

Then save the original ggplot() object:

myplot <- ggplot(mydf, aes(x = x, y = y)) + geom_smooth(method = "lm") + geom_point() + facet_wrap(~ letter, ncol = 2)

Then call facet_wrap_labeller() and feed the expression labels as an argument:

facet_wrap_labeller(myplot, labels = c(expression(paste("A or ", alpha)), expression(beta), expression(gamma), expression(delta)))

The expressions should now appear as the facet_wrap() labels.

like image 101
RTM Avatar answered Sep 28 '22 14:09

RTM