Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot facet_grid label superscript

Tags:

r

ggplot2

I am having trouble with putting subscript in facet_grid label. Here is an example of the work I have been trying to do.

df <- data.frame(species=gl(2,10,labels=c('sp1','sp2')),
                 age=sample(3:12,40,replace=T),
                 variable=gl(2,20,labels=c('N1P1 var','N2P1 var')),
                 value=rnorm(40))

test.plot <- ggplot(data=df,aes(x=age,y=value)) +
             geom_point() +
             facet_grid(variable~species)

Now I want to make by vertical facet label as 'N[1]P[1] var' and so on, where the numbers in the squared bracket means subscript.

I have consulted some helps in this platform regarding this, but none helped me. I have used expression, bquote as suggested, but nothing worked!

like image 908
Harun Rashid Avatar asked Dec 25 '22 09:12

Harun Rashid


1 Answers

You need to do 2 things: first, make your labels as plotmath expressions

variable_labels <- 
  c(expression(paste(N[1],P[1]~var)), expression(paste(N[2],P[1]~var)))

df <- data.frame(species=gl(2,10,labels=c('sp1','sp2')),
                 age=sample(3:12,40,replace=T),
                 variable=gl(2,20,labels=variable_labels),
                 value=rnorm(40))

And then change the default labeller function in facet_grid to "label_parsed"

test.plot <- ggplot(data=df,aes(x=age,y=value)) +
  geom_point() +
  facet_grid(variable~species, labeller = "label_parsed")

Resulting plot

like image 91
inscaven Avatar answered Dec 28 '22 08:12

inscaven