user3607944
user3607944

Reputation: 31

R how to add text (with mtext?) when plotting with the multiplot function from cookbook-r

I use the multiplot function from here to stack my numerous graphs of the form graph<-ggplot(...) with the line

png(filename = "qwerty.png", width = 1024, height = 1024, units = "px", 
    pointsize = 11, bg = "white",  res = 150)
multiplot(graph1,graph2,...., layout=matrix(c(1,2,3,4,5,6,7,8), nrow=8, 
          byrow=TRUE))
dev.off()

I want to add a few lines of text above the first graph, and the text could have complex editing with bold face for some letters for instance.

I tried to use, in placing it before and after multiplot

mtext(expression(paste("only ", bold("a"), " should be bold")), 1, 1)

but I get the error

Error in mtext(expression(paste("only ", bold("a"), " should be bold")),  : 
  plot.new has not been called yet`

Is it better to stack up another empty graph with my text ''as the graph'' ? If so, how can I do it ?

these data can be used to build the graphs for instance

p1 <- ggplot((subset(mtcars, gear==4)), aes(x=mpg, y=hp)) + 
      geom_point() +
      ggtitle("4 gears")
p2<-ggplot((subset(mtcars, gear==3)), aes(x=mpg, y=hp)) +
    geom_point() +
    ggtitle("3 gears")
multiplot(p1, p2, cols=2)

Upvotes: 1

Views: 1525

Answers (1)

Ruthger Righart
Ruthger Righart

Reputation: 4921

Instead of multiplot you could use grid.arrange:

library(gridExtra)

grid.arrange(arrangeGrob(p1,p2,ncol=2, nrow=1), main = "Here your title should be inserted",nrow=1)

If you want to adapt some text parameters, the following could help:

grid.arrange(arrangeGrob(p1,p2,ncol=2, nrow=1), main = textGrob("Here your title should be inserted",gp=gpar(fontsize=16, font=2)))

To save the file:

png("example-plot.png")
grid.arrange(arrangeGrob(p1,p2,ncol=2, nrow=1), main = textGrob("Here your title should be inserted",gp=gpar(fontsize=16, font=2)))
dev.off()

Upvotes: 1

Related Questions