Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a title for a grid.layout figure in ggplot2? [duplicate]

Tags:

r

ggplot2

I am using grid.layout() function to arrange a number of plots in one single figure. However, I do not know how to add a main title for the whole figure (at the mid-top of the figure)?

Does anybody know this and can help me out? Many thanks!

like image 292
Jin peng Avatar asked May 05 '16 13:05

Jin peng


People also ask

Does par () work with Ggplot?

One disadvantage for par() is that it cannot work for ggplot, we can see below that the plot should appear on the upper left of the page, but it just happen as if par() isn't written here.

How do I show multiple Ggplots in R?

To arrange multiple ggplot2 graphs on the same page, the standard R functions - par() and layout() - cannot be used. The basic solution is to use the gridExtra R package, which comes with the following functions: grid. arrange() and arrangeGrob() to arrange multiple ggplots on one page.

How do you make a grid plot in R?

Creating a Grid of Plots To do this, you use the parameter value mfrow=c(x,y) where x is the number of rows that you wish to have in your plot and y is the number of columns. When you plot, R will place each plot, in order by row within the grid that you define using mfrow .


1 Answers

I personally like this solution provided by cowplot maintainers on github:

Make two plots

p1 <- ggplot(mtcars, aes(x=disp, y=mpg)) + geom_point(colour = "blue") + background_grid(minor='none')
p2 <- ggplot(mtcars, aes(x=hp, y=mpg)) + geom_point(colour = "green") + background_grid(minor='none')

Use cowplot::plot_grid to combine the plots

p <- plot_grid(p1, p2, labels=c('A', 'B'))

Make a title

title <- ggdraw() + draw_label("MPG declines with displacement and horsepower", fontface='bold')

Add title

plot_grid(title, p, ncol=1, rel_heights=c(0.1, 1)) # rel_heights values control title margins
like image 127
Andrew Taylor Avatar answered Jan 04 '23 04:01

Andrew Taylor