7

Suppose I have the data and plot as follows:

mydata = data.frame(x=rnorm(4), y=runif(4), tau=c(0,0,1,1))
ggplot(mydata) + geom_point(aes(x=x, y=y)) + facet_wrap(~ tau)

I would like the facet labels to read "tau=0" and "tau=1", respectively, with tau formatted as its greek symbol. I know from another question that using the labeller label_parsed will format the letter tau by itself, but the equal sign seems to complicate things. An ideal solution would not require me to change the data (i.e. make tau a factor and name its levels), but I will take whatever works :)

Community
  • 1
  • 1
mitchus
  • 4,677
  • 3
  • 35
  • 70

2 Answers2

12

here a solution with facet_grid adn indexing the tau by its levels.

mydata = data.frame(x=rnorm(4), y=runif(4), tau=c(0,0,1,1))
ggplot(mydata) + geom_point(aes(x=x, y=y)) +
         facet_grid(~ tau,labeller = label_bquote(tau ^ .(x)))

enter image description here

Edit To get the "tau=0" and "tau=1"

facet_grid(~ tau,labeller = label_bquote(tau == .(x)))

Edit2 second variable sigma

I find this solution, by defining a custom labeller. Hope someone ( ggplot2 guys ) give me a simpler solution.

enter image description here

my.label_bquote <- function (expr1 = (tau == .(x)),expr2 = (sigma == .(x))) 
{
   quoted1<- substitute(expr1)
   quoted2 <- substitute(expr2)
   function(variable, value) {
      value <- as.character(value)
      if(variable == 'tau')
         lapply(value, function(x)
               eval(substitute(bquote(expr1, list(x = x)),list(expr1 = quoted1))))
      else
         lapply(value, function(x) 
               eval(substitute(bquote(expr2, list(x = x)),list(expr2 = quoted2))))
   }
}

mydata = data.frame(x=rnorm(4), y=runif(4), tau=c(0,0,1,1),sigma=c(2,2,3,3))
ggplot(mydata) + geom_point(aes(x=x, y=y)) +
  facet_grid(sigma ~ tau,labeller = my.label_bquote())
agstudy
  • 119,832
  • 17
  • 199
  • 261
  • Nice! Can this also be extended to two dimensions? E.g. if I have a second variable sigma I want to facet on, using `facet_grid`. – mitchus Jan 06 '13 at 14:31
  • 1
    The second variable solution is very "single use" but it worked for me after a little modification. In particular, I removed the parentheses around values to `expr1` and `expr2` and commented out the `browser()` call. Also the `variable == 'tau'` had to be changed for my application. – Zoë Clark Oct 17 '14 at 18:57
  • @ZoëClark Thank you for you feedback. I removed the browser statement. – agstudy Oct 17 '14 at 19:19
2

There is an easier solution to this. The simulated data variable names have been changed for clarity in how they work within the labeller argument.

mydata = data.frame(x=rnorm(4), y=runif(4), tauvar=c(0,0,1,1),sigmavar=c(2,2,3,3))

ggplot(mydata) + 
   geom_point(aes(x=x, y=y)) +
   facet_grid(sigmavar ~ tauvar,labeller = label_bquote(sigma==.(sigmavar),
                                                   tau==.(tauvar)))
Val N.
  • 21
  • 1