Meso
Meso

Reputation: 1435

How to use subscript in titles of facet grid in ggplot2

I am unable to create a subscript for the last subtitle (pm10). How can I capitalize pm and create subscript "10". Presently the title is pm10.

library(dlnm)
library(ggplot2)
library(reshape2)
library(plyr)
data <- chicagoNMMAPS
data1<-data[c(1,7:9,13)]
dmelt = melt(data1, id.vars = 'date')


ggplot(dmelt, aes(x = date, y = value)) + 
geom_line() + 
theme_bw() +
facet_wrap(~ variable, scales = 'free_y', ncol = 1)+ 
theme(strip.text.x = element_text(size=14,face="bold"),
strip.background = element_rect(colour="")) + 
labs(x = "Date") +
theme(axis.title=element_text(face="bold",size="14"),axis.text=element_text(size=14,face="bold")) +
theme(#panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
strip.background = element_blank(),
panel.border = element_rect(colour = "black"))

Upvotes: 1

Views: 2368

Answers (1)

Max Candocia
Max Candocia

Reputation: 4385

So, you can do this using a labeller function. Unfortunately, facet_wrap does not currently have this, but facet_grid does.

vnames <-list(
'death' = 'death',
'cvd' = 'cvd',
'resp' = 'resp',
'pm10' = bquote(pm[10]))

vlabeller <- function(variable,value){
  return(vnames[value])
}

bquote is a flexible way to use expressions. More can be found here. You can see more Then, simply change the original facet_wrap function to the following:

facet_grid(variable~., scales = 'free_y', labeller = vlabeller)

However, its appearance is a bit different than what you may want. In that case, you can deal directly with the elements of the plot itself, but it's much more cumbersome. The method is described here: https://stackoverflow.com/a/19298442/1362215

Upvotes: 3

Related Questions