Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while adding main title with subscript in gridExtra

I am trying to arrange a few plots generated by ggplot2using the gridExtra package.

library(ggplot2)
library(gridExtra)
p1 <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()
p2 <- ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_point()
p3 <- ggplot(iris, aes(Species, Sepal.Width)) + geom_point()
p4 <- ggplot(iris, aes(Sepal.Width, Petal.Width)) + geom_point()
grid.arrange(main="CO2Exp", p1, p2, p3, p4, ncol=2)

When I try to have a main title, the follwing works fine.

grid.arrange(main="CO2Exp", p1, p2, p3, p4, ncol=2)

But when I try with expression to get a subscript,

grid.arrange(main=expression(paste(CO[2], "Exp")), p1, p2, p3, p4, ncol=2)

I get the following error

Error in valid.data(rep(units, length.out = length(x)), data) : 
  no 'grob' supplied for 'grobwidth/height' unit

How to fix this?

I am using R_3.1.3, gridExtra_0.9.1 and ggplot2_1.0.1

like image 608
Crops Avatar asked Apr 15 '15 12:04

Crops


1 Answers

Create a textGrob explicitly:

grid.arrange(main = textGrob(label = expression(paste(CO[2], "Exp"))), 
             p1, p2, p3, p4, ncol=2)

Edit (16/07/2015): with gridExtra >= 2.0.0, the main parameter has been renamed top. See ?arrangeGrob for details.

like image 102
Roland Avatar answered Nov 15 '22 23:11

Roland