<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page"> Easy Guides</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p></p>
<p>  </p>
<div>
<p></p>
<p>To arrange <strong>multiple</strong> <strong>ggplot2</strong> graphs on the same page, the standard R functions – <em>par()</em> and <em>layout()</em> – cannot be used.</p>
<p>The basic solution is to use the <a rel="nofollow" href="https://github.com/baptiste/gridextra/wiki/arrangeGrob" target="_blank"><strong>gridExtra</strong></a> R package, which comes with the following functions:</p>
<ul>
<li><em>grid.arrange</em>() and <em>arrangeGrob</em>() to arrange multiple ggplots on one page</li>
<li><em>marrangeGrob</em>() for arranging multiple ggplots over multiple pages.</li>
</ul>
<p>However, these functions makes no attempt at aligning the plot panels; instead, the plots are simply placed into the grid as they are, and so the axes are not aligned.</p>
<p>If axis alignment is required, you can switch to the <a rel="nofollow" href="https://cran.r-project.org/web/packages/cowplot/vignettes/introduction.html" target="_blank"><strong>cowplot</strong></a> package, which include the function <strong>plot_grid</strong>() with the argument <em>align</em>. However, the cowplot package doesn’t contain any solution for multi-pages layout. Therefore, we provide the function <strong>ggarrange</strong>() [in ggpubr], a wrapper around the plot_grid() function, to arrange multiple ggplots over multiple pages. It can also create a common unique legend for multiple plots.</p>
<div>
<p>
This article will show you, step by step, how to combine multiple <strong>ggplots</strong> on the same page, as well as, over multiple pages, using helper functions available in the following R package: <a rel="nofollow" href="http://www.sthda.com/english/rpkgs/ggpubr/index.html" target="_blank"><strong>ggpubr</strong> R package</a>, <strong>cowplot</strong> and <strong>gridExtra</strong>. We’ll also describe how to export the arranged plots to a file.
</p>
</div>
<p><img alt="Arrange multiple ggplots" src="https://i1.wp.com/www.sthda.com/sthda/RDoc/images/arrange-multiple-ggplots.png?w=456" data-recalc-dims="1"></p>
<p>Related articles:</p>
<div>
<ul>
<li>
<a rel="nofollow" href="http://www.sthda.com/english/wiki/bar-plots-and-modern-alternatives" target="_blank">Bar Plots and Modern Alternatives</a>
</li>
<li>
<a rel="nofollow" href="http://www.sthda.com/english/wiki/facilitating-exploratory-data-visualization-application-to-tcga-genomic-data" target="_blank">Facilitating Exploratory Data Visualization: Application to TCGA Genomic Data</a>
</li>
<li>
<a rel="nofollow" href="http://www.sthda.com/english/wiki/add-p-values-and-significance-levels-to-ggplots" target="_blank">Add P-values and Significance Levels to ggplots</a>
</li>
</ul>
</div>
<p><strong>Contents</strong>:</p>
<div>
<ul>
<li><a rel="nofollow" href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page#prerequisites" target="_blank">Prerequisites</a></li>
<li><a rel="nofollow" href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page#create-some-plots" target="_blank">Create some plots</a></li>
<li><a rel="nofollow" href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page#arrange-on-one-page" target="_blank">Arrange on one page</a></li>
<li><a rel="nofollow" href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page#annotate-the-arranged-figure" target="_blank">Annotate the arranged figure</a></li>
<li><a rel="nofollow" href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page#align-plot-panels" target="_blank">Align plot panels</a></li>
<li><a rel="nofollow" href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page#change-columnrow-span-of-a-plot" target="_blank">Change column/row span of a plot</a></li>
<li><a rel="nofollow" href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page#use-common-legend-for-combined-ggplots" target="_blank">Use common legend for combined ggplots</a></li>
<li><a rel="nofollow" href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page#scatter-plot-with-marginal-density-plots" target="_blank">Scatter plot with marginal density plots</a></li>
<li><a rel="nofollow" href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page#mix-table-text-and-ggplot" target="_blank">Mix table, text and ggplot2 graphs</a></li>
<li><a rel="nofollow" href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page#insert-a-graphical-element-inside-a-ggplot" target="_blank">Insert a graphical element inside a ggplot</a></li>
<li><a rel="nofollow" href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page#arrange-over-multiple-pages" target="_blank">Arrange over multiple pages</a></li>
<li><a rel="nofollow" href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page#nested-layout-with-ggarrange" target="_blank">Nested layout with ggarrange()</a></li>
<li><a rel="nofollow" href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page#export-plots" target="_blank">Export plots</a></li>
<li><a rel="nofollow" href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page#acknoweledgment" target="_blank">Acknoweledgment</a></li>
<li><a rel="nofollow" href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page#infos" target="_blank">Infos</a></li>
</ul>
</div>
<div>
<h2>Prerequisites</h2>
<div>
<h3>Required R package</h3>
<p>You need to install the R package <a rel="nofollow" href="http://www.sthda.com/english/rpkgs/ggpubr" target="_blank">ggpubr (version >= 0.1.3)</a>, to easily create ggplot2-based publication ready plots.</p>
<p>We recommend to install the latest developmental version from <a rel="nofollow" href="https://github.com/kassambara/ggpubr" target="_blank">GitHub</a> as follow:</p>
<pre><code>if(!require(devtools)) install.packages(&quot;devtools&quot;)
devtools::install_github(&quot;kassambara/ggpubr&quot;)</code></pre>
<p>If installation from Github failed, then try to install from <a rel="nofollow" href="https://cran.r-project.org/package=ggpubr" target="_blank">CRAN</a> as follow:</p>
<pre><code>install.packages(&quot;ggpubr&quot;)</code></pre>
<div>
<p>
Note that, the installation of <strong>ggpubr</strong> will install the <strong>gridExtra</strong> and the <strong>cowplot</strong> package; so you don’t need to re-install them.
</p>
</div>
<p>Load ggpubr:</p>
<pre><code>library(ggpubr)</code></pre>
</div>
<div>
<h3>Demo data sets</h3>
<p>Data: <a rel="nofollow" href="http://www.sthda.com/english/wiki/r-built-in-data-sets#toothgrowth" target="_blank">ToothGrowth</a> and <a rel="nofollow" href="http://www.sthda.com/english/wiki/r-built-in-data-sets#mtcars-motor-trend-car-road-tests" target="_blank">mtcars</a> data sets.</p>
<pre><code># ToothGrowth
data(&quot;ToothGrowth&quot;)
head(ToothGrowth)</code></pre>
<pre><code>   len supp dose
1  4.2   VC  0.5
2 11.5   VC  0.5
3  7.3   VC  0.5
4  5.8   VC  0.5
5  6.4   VC  0.5
6 10.0   VC  0.5</code></pre>
<pre><code># mtcars 
data(&quot;mtcars&quot;)
mtcars$name &lt;- rownames(mtcars)
mtcars$cyl &lt;- as.factor(mtcars$cyl)
head(mtcars[, c(&quot;name&quot;, &quot;wt&quot;, &quot;mpg&quot;, &quot;cyl&quot;)])</code></pre>
<pre><code>                               name    wt  mpg cyl
Mazda RX4                 Mazda RX4 2.620 21.0   6
Mazda RX4 Wag         Mazda RX4 Wag 2.875 21.0   6
Datsun 710               Datsun 710 2.320 22.8   4
Hornet 4 Drive       Hornet 4 Drive 3.215 21.4   6
Hornet Sportabout Hornet Sportabout 3.440 18.7   8
Valiant                     Valiant 3.460 18.1   6</code></pre>
</div>
</div>
<div>
<h2>Create some plots</h2>
<p>Here, we’ll use ggplot2-based plotting functions available in <a rel="nofollow" href="http://www.sthda.com/english/rpkgs/ggpubr" target="_blank">ggpubr</a>. You can use any ggplot2 functions to create the plots that you want for arranging them later.</p>
<p>We’ll start by creating 4 different plots:</p>
<ul>
<li>Box plots and dot plots using the <em>ToothGrowth</em> data set</li>
<li>Bar plots and scatter plots using the <em>mtcars</em> data set</li>
</ul>
<p>You’ll learn how to combine these plots in the next sections using specific functions.</p>
<ul>
<li><strong>Create a box plot and a dot plot</strong>:</li>
</ul>
<pre><code># Box plot (bp)
bxp &lt;- ggboxplot(ToothGrowth, x = &quot;dose&quot;, y = &quot;len&quot;,
                 color = &quot;dose&quot;, palette = &quot;jco&quot;)
bxp
# Dot plot (dp)
dp &lt;- ggdotplot(ToothGrowth, x = &quot;dose&quot;, y = &quot;len&quot;,
                 color = &quot;dose&quot;, palette = &quot;jco&quot;, binwidth = 1)
dp</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i1.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-box-dot-plot-1.png?w=336" data-recalc-dims="1"><img alt="Arrange multiple ggplots on the same page" src="https://i2.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-box-dot-plot-2.png?w=336" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
<ul>
<li><strong>Create an ordered bar plot and a scatter plot</strong>:</li>
</ul>
<p>Create ordered bar plots. Change the fill color by the grouping variable “cyl”. Sorting will be done globally, but not by groups.</p>
<pre><code># Bar plot (bp)
bp &lt;- ggbarplot(mtcars, x = &quot;name&quot;, y = &quot;mpg&quot;,
          fill = &quot;cyl&quot;,               # change fill color by cyl
          color = &quot;white&quot;,            # Set bar border colors to white
          palette = &quot;jco&quot;,            # jco journal color palett. see ?ggpar
          sort.val = &quot;asc&quot;,           # Sort the value in ascending order
          sort.by.groups = TRUE,      # Sort inside each group
          x.text.angle = 90           # Rotate vertically x axis texts
          )
bp + font(&quot;x.text&quot;, size = 8)
# Scatter plots (sp)
sp &lt;- ggscatter(mtcars, x = &quot;wt&quot;, y = &quot;mpg&quot;,
                add = &quot;reg.line&quot;,               # Add regression line
                conf.int = TRUE,                # Add confidence interval
                color = &quot;cyl&quot;, palette = &quot;jco&quot;, # Color by groups &quot;cyl&quot;
                shape = &quot;cyl&quot;                   # Change point shape by groups &quot;cyl&quot;
                )+
  stat_cor(aes(color = cyl), label.x = 3)       # Add correlation coefficient
sp</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i2.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-ordered-bar-plots-1.png?w=355" data-recalc-dims="1"><img alt="Arrange multiple ggplots on the same page" src="https://i0.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-ordered-bar-plots-2.png?w=355" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
</div>
<div>
<h2>Arrange on one page</h2>
<p>To arrange multiple ggplots on one single page, we’ll use the function <strong>ggarrange</strong>()[in <strong>ggpubr</strong>], which is a wrapper around the function <em>plot_grid</em>() [in <em>cowplot</em> package]. Compared to the standard function <em>plot_grid</em>(), <strong>ggarange</strong>() can arrange multiple ggplots over multiple pages.</p>
<pre><code>ggarrange(bxp, dp, bp + rremove(&quot;x.text&quot;), 
          labels = c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;),
          ncol = 2, nrow = 2)</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i2.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-ggarrange-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
<p>Alternatively, you can also use the function <strong>plot_grid</strong>() [in <strong>cowplot</strong>]:</p>
<pre><code>library(&quot;cowplot&quot;)
plot_grid(bxp, dp, bp + rremove(&quot;x.text&quot;), 
          labels = c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;),
          ncol = 2, nrow = 2)</code></pre>
<p>or, the function <strong>grid.arrange</strong>() [in <strong>gridExtra</strong>]:</p>
<pre><code>library(&quot;gridExtra&quot;)
grid.arrange(bxp, dp, bp + rremove(&quot;x.text&quot;), 
             ncol = 2, nrow = 2)</code></pre>
</div>
<div>
<h2>Annotate the arranged figure</h2>
<p>R function: <strong>annotate_figure</strong>() [in ggpubr].</p>
<pre><code>figure &lt;- ggarrange(sp, bp + font(&quot;x.text&quot;, size = 10),
                    ncol = 1, nrow = 2)
annotate_figure(figure,
                top = text_grob(&quot;Visualizing mpg&quot;, color = &quot;red&quot;, face = &quot;bold&quot;, size = 14),
                bottom = text_grob(&quot;Data source: \n mtcars data set&quot;, color = &quot;blue&quot;,
                                   hjust = 1, x = 1, face = &quot;italic&quot;, size = 10),
                left = text_grob(&quot;Figure arranged using ggpubr&quot;, color = &quot;green&quot;, rot = 90),
                right = &quot;I'm done, thanks :-)!&quot;,
                fig.lab = &quot;Figure 1&quot;, fig.lab.face = &quot;bold&quot;
                )</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i1.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-annotate-arranged-ggplots-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
<div>
<p>
Note that, the function annotate_figure() supports any ggplots.
</p>
</div>
</div>
<div>
<h2>Align plot panels</h2>
<p>A real use case is, for example, when plotting <a rel="nofollow" href="http://www.sthda.com/english/wiki/survival-analysis-basics" target="_blank">survival curves</a> with the risk table placed under the main plot.</p>
<p>To illustrate this case, we’ll use the survminer package. First, install it using <em>install.packages(“survminer”)</em>, then type this:</p>
<pre><code># Fit survival curves
library(survival)
fit &lt;- survfit( Surv(time, status) ~ adhere, data = colon )
# Plot survival curves
library(survminer)
ggsurv &lt;- ggsurvplot(fit, data = colon, 
                     palette = &quot;jco&quot;,                              # jco palette
                     pval = TRUE, pval.coord = c(500, 0.4),        # Add p-value
                     risk.table = TRUE                            # Add risk table
                     )
names(ggsurv)</code></pre>
<pre><code>[1] &quot;plot&quot;           &quot;table&quot;          &quot;data.survplot&quot;  &quot;data.survtable&quot;</code></pre>
<p>ggsurv is a list including the components:</p>
<ul>
<li><em>plot</em>: survival curves</li>
<li><em>table</em>: the risk table plot</li>
</ul>
<p>You can arrange the survival plot and the risk table as follow:</p>
<pre><code>ggarrange(ggsurv$plot, ggsurv$table, heights = c(2, 0.7),
          ncol = 1, nrow = 2)</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i0.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-align-plot-panels-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
<div>
<p>
It can be seen that the axes of the survival plot and the risk table are not aligned vertically. To align them, specify the argument <strong>align</strong> as follow.
</p>
</div>
<pre><code>ggarrange(ggsurv$plot, ggsurv$table, heights = c(2, 0.7),
          ncol = 1, nrow = 2, align = &quot;v&quot;)</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i1.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-align-plot-panels-2-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
</div>
<div>
<h2>Change column/row span of a plot</h2>
<div>
<h3>Use ggpubr R package</h3>
<p>We’ll use nested <strong>ggarrange</strong>() functions to change column/row span of plots.</p>
<p>For example, using the R code below:</p>
<ul>
<li>the scatter plot (sp) will live in the first row and spans over two columns</li>
<li>the box plot (bxp) and the dot plot (dp) will be first arranged and will live in the second row with two different columns</li>
</ul>
<pre><code>ggarrange(sp,                                                 # First row with scatter plot
          ggarrange(bxp, dp, ncol = 2, labels = c(&quot;B&quot;, &quot;C&quot;)), # Second row with box and dot plots
          nrow = 2, 
          labels = &quot;A&quot;                                        # Labels of the scatter plot
          ) </code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i0.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-ggarrange-column-row-span-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
</div>
<div>
<h3>Use cowplot R package</h3>
<p>The combination of the functions <strong>ggdraw</strong>() + <strong>draw_plot</strong>() + <strong>draw_plot_label</strong>() [in <strong>cowplot</strong>] can be used to place graphs at particular locations with a particular size.</p>
<p><strong>ggdraw(). Initialize an empty drawing canvas</strong>:</p>
<pre><code>ggdraw()</code></pre>
<div>
<p>
Note that, by default, coordinates run from 0 to 1, and the point (0, 0) is in the lower left corner of the canvas (see the figure below).
</p>
</div>
<p><img alt="draw_plot" src="https://i1.wp.com/www.sthda.com/sthda/RDoc/images/canva.png?w=456" data-recalc-dims="1"></p>
<p><strong>draw_plot(). Places a plot somewhere onto the drawing canvas</strong>:</p>
<pre><code>draw_plot(plot, x = 0, y = 0, width = 1, height = 1)</code></pre>
<ul>
<li><em>plot</em>: the plot to place (ggplot2 or a gtable)</li>
<li><em>x, y</em>: The x/y location of the lower left corner of the plot.</li>
<li><em>width, height</em>: the width and the height of the plot</li>
</ul>
<p><strong>draw_plot_label()</strong>. Adds a plot label to the upper left corner of a graph. It can handle vectors of labels with associated coordinates.</p>
<pre><code>draw_plot_label(label, x = 0, y = 1, size = 16, ...)</code></pre>
<ul>
<li><em>label</em>: a vector of labels to be drawn</li>
<li><em>x, y</em>: Vector containing the x and y position of the labels, respectively.</li>
<li><em>size</em>: Font size of the label to be drawn</li>
</ul>
<p>For example, you can combine multiple plots, with particular locations and different sizes, as follow:</p>
<pre><code>library(&quot;cowplot&quot;)
ggdraw() +
  draw_plot(bxp, x = 0, y = .5, width = .5, height = .5) +
  draw_plot(dp, x = .5, y = .5, width = .5, height = .5) +
  draw_plot(bp, x = 0, y = 0, width = 1, height = 0.5) +
  draw_plot_label(label = c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;), size = 15,
                  x = c(0, 0.5, 0), y = c(1, 1, 0.5))</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i2.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-cowplot-row-column-span-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
</div>
<div>
<h3>Use gridExtra R package</h3>
<p>The function <strong>arrangeGrop</strong>() [in <strong>gridExtra</strong>] helps to change the row/column span of a plot.</p>
<p>For example, using the R code below:</p>
<ul>
<li>the scatter plot (sp) will live in the first row and spans over two columns</li>
<li>the box plot (bxp) and the dot plot (dp) will live in the second row with two plots in two different columns</li>
</ul>
<pre><code>library(&quot;gridExtra&quot;)
grid.arrange(sp,                             # First row with one plot spaning over 2 columns
             arrangeGrob(bxp, dp, ncol = 2), # Second row with 2 plots in 2 different columns
             nrow = 2)                       # Number of rows</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i1.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-grid-arrange-column-row-span-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
<p>It’s also possible to use the argument <strong>layout_matrix</strong> in the <strong>grid.arrange</strong>() function, to create a complex layout.</p>
<p>In the R code below <em>layout_matrix</em> is a 2x2 matrix (2 columns and 2 rows). The first row is all 1s, that’s where the first plot lives, spanning the two columns; the second row contains plots 2 and 3 each occupying one column.</p>
<pre><code>grid.arrange(bp,                                    # bar plot spaning two columns
             bxp, sp,                               # box plot and scatter plot
             ncol = 2, nrow = 2, 
             layout_matrix = rbind(c(1,1), c(2,3)))</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i1.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-grid-arrange-layout-matrix-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
<div>
<p>
Note that, it’s also possible to annotate the output of the <em>grid.arrange</em>() function using the helper function <strong>draw_plot_label</strong>() [in cowplot].
</p>
</div>
<p>To easily annotate the <em>grid.arrange</em>() / <em>arrangeGrob</em>() output (a gtable), you should first transform it to a ggplot using the function <em>as_ggplot</em>() [in ggpubr ]. Next you can annotate it using the function <em>draw_plot_label</em>() [in cowplot].</p>
<pre><code>library(&quot;gridExtra&quot;)
library(&quot;cowplot&quot;)
# Arrange plots using arrangeGrob
# returns a gtable (gt)
gt &lt;- arrangeGrob(bp,                               # bar plot spaning two columns
             bxp, sp,                               # box plot and scatter plot
             ncol = 2, nrow = 2, 
             layout_matrix = rbind(c(1,1), c(2,3)))
# Add labels to the arranged plots
p &lt;- as_ggplot(gt) +                                # transform to a ggplot
  draw_plot_label(label = c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;), size = 15,
                  x = c(0, 0, 0.5), y = c(1, 0.5, 0.5)) # Add labels
p</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i2.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-add-labels-to-grid-arrange-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
<div>
<p>
In the above R code, we used <em>arrangeGrob</em>() instead of <em>grid.arrange</em>().
</p>
<p>
Note that, the main difference between these two functions is that, <em>grid.arrange</em>() draw automatically the output of the arranged plots.
</p>
<p>
As we want to annotate the arranged plots before drawing it, the function <em>arrangeGrob</em>() is preferred in this case.
</p>
</div>
</div>
<div>
<h3>Use grid R package</h3>
<p>The grid R package can be used to create a complex layout with the help of the function <strong>grid.layout</strong>(). It provides also the helper function <strong>viewport</strong>() to define a region or a viewport on the layout. The function <strong>print</strong>() is used to place plots in a specified region.</p>
<p>The different steps can be summarized as follow :</p>
<ol>
<li>Create plots : p1, p2, p3, ….</li>
<li>Move to a new page on a grid device using the function <strong>grid.newpage</strong>()</li>
<li>Create a layout 2X2 - number of columns = 2; number of rows = 2</li>
<li>Define a grid viewport : a rectangular region on a graphics device</li>
<li>Print a plot into the viewport</li>
</ol>
<pre><code>library(grid)
# Move to a new page
grid.newpage()
# Create layout : nrow = 3, ncol = 2
pushViewport(viewport(layout = grid.layout(nrow = 3, ncol = 2)))
# A helper function to define a region on the layout
define_region &lt;- function(row, col){
  viewport(layout.pos.row = row, layout.pos.col = col)
} 
# Arrange the plots
print(sp, vp = define_region(row = 1, col = 1:2))   # Span over two columns
print(bxp, vp = define_region(row = 2, col = 1))
print(dp, vp = define_region(row = 2, col = 2))
print(bp + rremove(&quot;x.text&quot;), vp = define_region(row = 3, col = 1:2))</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i0.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-viewport-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
</div>
</div>
<div>
<h2>Use common legend for combined ggplots</h2>
<p>To place a common unique legend in the margin of the arranged plots, the function <strong>ggarrange</strong>() [in ggpubr] can be used with the following arguments:</p>
<ul>
<li><em>common.legend = TRUE</em>: place a common legend in a margin</li>
<li><em>legend</em>: specify the legend position. Allowed values include one of c(“top”, “bottom”, “left”, “right”)</li>
</ul>
<pre><code>ggarrange(bxp, dp, labels = c(&quot;A&quot;, &quot;B&quot;),
          common.legend = TRUE, legend = &quot;bottom&quot;)</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i2.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-common-legend-for-combined-ggplots-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
</div>
<div>
<h2>Scatter plot with marginal density plots</h2>
<pre><code># Scatter plot colored by groups (&quot;Species&quot;)
sp &lt;- ggscatter(iris, x = &quot;Sepal.Length&quot;, y = &quot;Sepal.Width&quot;,
                color = &quot;Species&quot;, palette = &quot;jco&quot;,
                size = 3, alpha = 0.6)+
  border()                                         
# Marginal density plot of x (top panel) and y (right panel)
xplot &lt;- ggdensity(iris, &quot;Sepal.Length&quot;, fill = &quot;Species&quot;,
                   palette = &quot;jco&quot;)
yplot &lt;- ggdensity(iris, &quot;Sepal.Width&quot;, fill = &quot;Species&quot;, 
                   palette = &quot;jco&quot;)+
  rotate()
# Cleaning the plots
yplot &lt;- yplot + clean_theme() 
xplot &lt;- xplot + clean_theme()
# Arranging the plot
ggarrange(xplot, NULL, sp, yplot, 
          ncol = 2, nrow = 2,  align = &quot;hv&quot;, 
          widths = c(2, 1), heights = c(1, 2),
          common.legend = TRUE)</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i0.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-marginal-plot-grouped-data-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
</div>
<div>
<h2>Mix table, text and ggplot2 graphs</h2>
<p>In this section, we’ll show how to plot a table and text alongside a chart. The iris data set will be used.</p>
<p>We start by creating the following plots:</p>
<ol>
<li>a <strong>density plot</strong> of the variable “Sepal.Length”. R function: <strong>ggdensity</strong>() [in ggpubr]</li>
<li>a plot of the <strong>summary table</strong> containing the descriptive statistics (mean, sd, … ) of Sepal.Length.
<ul>
<li>R function for computing descriptive statistics: <strong>desc_statby</strong>() [in ggpubr].</li>
<li>R function to draw a textual table: <strong>ggtexttable</strong>() [in ggpubr].</li>
</ul>
</li>
<li>a plot of a text <strong>paragraph</strong>. R function: <strong>ggparagraph</strong>() [in ggpubr].</li>
</ol>
<p>We finish by arranging/combining the three plots using the function <strong>ggarrange</strong>() [in ggpubr]</p>
<pre><code># Density plot of &quot;Sepal.Length&quot;
#::::::::::::::::::::::::::::::::::::::
density.p &lt;- ggdensity(iris, x = &quot;Sepal.Length&quot;, 
                       fill = &quot;Species&quot;, palette = &quot;jco&quot;)
# Draw the summary table of Sepal.Length
#::::::::::::::::::::::::::::::::::::::
# Compute descriptive statistics by groups
stable &lt;- desc_statby(iris, measure.var = &quot;Sepal.Length&quot;,
                      grps = &quot;Species&quot;)
stable &lt;- stable[, c(&quot;Species&quot;, &quot;length&quot;, &quot;mean&quot;, &quot;sd&quot;)]
# Summary table plot, medium orange theme
stable.p &lt;- ggtexttable(stable, rows = NULL, 
                        theme = ttheme(&quot;mOrange&quot;))
# Draw text
#::::::::::::::::::::::::::::::::::::::
text &lt;- paste(&quot;iris data set gives the measurements in cm&quot;,
              &quot;of the variables sepal length and width&quot;,
              &quot;and petal length and width, respectively,&quot;,
              &quot;for 50 flowers from each of 3 species of iris.&quot;,
             &quot;The species are Iris setosa, versicolor, and virginica.&quot;, sep = &quot; &quot;)
text.p &lt;- ggparagraph(text = text, face = &quot;italic&quot;, size = 11, color = &quot;black&quot;)
# Arrange the plots on the same page
ggarrange(density.p, stable.p, text.p, 
          ncol = 1, nrow = 3,
          heights = c(1, 0.5, 0.3))</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i0.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-add-table-add-text-data-visualization-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
</div>
<div>
<h2>Insert a graphical element inside a ggplot</h2>
<p>The function <strong>annotation_custom</strong>() [in ggplot2] can be used for adding tables, plots or other grid-based elements within the plotting area of a ggplot. The simplified format is :</p>
<pre><code>annotation_custom(grob, xmin, xmax, ymin, ymax)</code></pre>
<div>
<ul>
<li>
<strong>grob</strong>: the external graphical element to display
</li>
<li>
<strong>xmin, xmax</strong> : x location in data coordinates (horizontal location)
</li>
<li>
<strong>ymin, ymax</strong> : y location in data coordinates (vertical location)
</li>
</ul>
</div>
<div>
<h3>Place a table within a ggplot</h3>
<p>We’ll use the plots - density.p and stable.p - created in the previous section (@ref(mix-table-text-and-ggplot)).</p>
<pre><code>density.p + annotation_custom(ggplotGrob(stable.p),
                              xmin = 5.5, ymin = 0.7,
                              xmax = 8)</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i1.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-add-table-within-a-ggplot-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
</div>
<div>
<h3>Place a box plot within a ggplot</h3>
<ol>
<li>Create a scatter plot of y = “Sepal.Width” by x = “Sepal.Length” using the iris data set. R function <strong>ggscatter</strong>() [ggpubr]</li>
<li>Create separately the box plot of x and y variables with transparent background. R function: <strong>ggboxplot</strong>() [ggpubr].</li>
<li>Transform the box plots into graphical objects called a “grop” in Grid terminology. R function <strong>ggplotGrob</strong>() [ggplot2].</li>
<li>Place the box plot grobs inside the scatter plot. R function: <strong>annotation_custom</strong>() [ggplot2].</li>
</ol>
<div>
<p>
As the inset box plot overlaps with some points, a <em>transparent background</em> is used for the box plots.
</p>
</div>
<pre><code># Scatter plot colored by groups (&quot;Species&quot;)
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sp &lt;- ggscatter(iris, x = &quot;Sepal.Length&quot;, y = &quot;Sepal.Width&quot;,
                color = &quot;Species&quot;, palette = &quot;jco&quot;,
                size = 3, alpha = 0.6)
# Create box plots of x/y variables
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
# Box plot of the x variable
xbp &lt;- ggboxplot(iris$Sepal.Length, width = 0.3, fill = &quot;lightgray&quot;) +
  rotate() +
  theme_transparent()
# Box plot of the y variable
ybp &lt;- ggboxplot(iris$Sepal.Width, width = 0.3, fill = &quot;lightgray&quot;) +
  theme_transparent()
# Create the external graphical objects
# called a &quot;grop&quot; in Grid terminology
xbp_grob &lt;- ggplotGrob(xbp)
ybp_grob &lt;- ggplotGrob(ybp)
# Place box plots inside the scatter plot
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
xmin &lt;- min(iris$Sepal.Length); xmax &lt;- max(iris$Sepal.Length)
ymin &lt;- min(iris$Sepal.Width); ymax &lt;- max(iris$Sepal.Width)
yoffset &lt;- (1/15)*ymax; xoffset &lt;- (1/15)*xmax
# Insert xbp_grob inside the scatter plot
sp + annotation_custom(grob = xbp_grob, xmin = xmin, xmax = xmax, 
                       ymin = ymin-yoffset, ymax = ymin+yoffset) +
  # Insert ybp_grob inside the scatter plot
  annotation_custom(grob = ybp_grob,
                       xmin = xmin-xoffset, xmax = xmin+xoffset, 
                       ymin = ymin, ymax = ymax)</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i1.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-place-box-plot-within-scatter-plot-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
</div>
<div>
<h3>Add background image to ggplot2 graphs</h3>
<p><strong>Import the background image</strong>. Use either the function <strong>readJPEG</strong>() [in <em>jpeg</em> package] or the function <strong>readPNG</strong>() [in <em>png</em> package] depending on the format of the background image.</p>
<p>To test the example below, make sure that the <em>png</em> package is installed. You can install it using install.packages(“png”) R command.</p>
<pre><code># Import the image
img.file &lt;- system.file(file.path(&quot;images&quot;, &quot;background-image.png&quot;),
                        package = &quot;ggpubr&quot;)
img &lt;- png::readPNG(img.file)</code></pre>
<p><strong>Combine a ggplot with the background image</strong>. R function: <strong>background_image</strong>() [in ggpubr].</p>
<pre><code>library(ggplot2)
library(ggpubr)
ggplot(iris, aes(Species, Sepal.Length))+
  background_image(img)+
  geom_boxplot(aes(fill = Species), color = &quot;white&quot;)+
  fill_palette(&quot;jco&quot;)</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i1.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-ggplot2-with-background-image-1.png?w=432" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
<p>Change box plot fill color transparency by specifying the argument alpha. Value should be in [0, 1], where 0 is full transparency and 1 is no transparency.</p>
<pre><code>library(ggplot2)
library(ggpubr)
ggplot(iris, aes(Species, Sepal.Length))+
  background_image(img)+
  geom_boxplot(aes(fill = Species), color = &quot;white&quot;, alpha = 0.5)+
  fill_palette(&quot;jco&quot;)</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i0.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-ggplot2-with-background-image-transparency-1.png?w=432" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
<p>Another example, overlaying the France map and a ggplot2:</p>
<pre><code>mypngfile &lt;- download.file(&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/France_Flag_Map.svg/612px-France_Flag_Map.svg.png&quot;, 
                           destfile = &quot;france.png&quot;, mode = 'wb') 
img &lt;- png::readPNG('france.png') 
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  background_image(img)+
  geom_point(aes(color = Species), alpha = 0.6, size = 5)+
  color_palette(&quot;jco&quot;)+
  theme(legend.position = &quot;top&quot;)</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i1.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-overlay-ggplot2-with-country-map-1.png?w=384" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
</div>
</div>
<div>
<h2>Arrange over multiple pages</h2>
<p>If you have a long list of ggplots, say n = 20 plots, you may want to arrange the plots and to place them on multiple pages. With 4 plots per page, you need 5 pages to hold the 20 plots.</p>
<p>The function <strong>ggarrange</strong>() [in ggpubr] provides a convenient solution to arrange multiple ggplots over multiple pages. After specifying the arguments <em>nrow</em> and <em>ncol</em>, the function <strong>ggarrange</strong>() computes automatically the number of pages required to hold the list of the plots. It returns a list of arranged ggplots.</p>
<p>For example the following R code,</p>
<pre><code>multi.page &lt;- ggarrange(bxp, dp, bp, sp,
                        nrow = 1, ncol = 2)</code></pre>
<p>returns a list of two pages with two plots per page. You can visualize each page as follow:</p>
<pre><code>multi.page[[1]] # Visualize page 1
multi.page[[2]] # Visualize page 2</code></pre>
<p>You can also export the arranged plots to a pdf file using the function <strong>ggexport</strong>() [in ggpubr]:</p>
<pre><code>ggexport(multi.page, filename = &quot;multi.page.ggplot2.pdf&quot;)</code></pre>
<p>PDF file: <a rel="nofollow" href="http://www.slideshare.net/kassambara/multipageggplot2" target="_blank">Multi.page.ggplot2</a></p>
<p><iframe allowfullscreen src="http://www.slideshare.net/slideshow/embed_code/key/zT39z4AS2fVIY" width="450"><br>
</iframe></p>
<div>
<p>
Note that, it’s also possible to use the function <strong>marrangeGrob()</strong> [in gridExtra] to create a multi-pages output.
</p>
</div>
<pre><code>library(gridExtra)
res &lt;- marrangeGrob(list(bxp, dp, bp, sp), nrow = 1, ncol = 2)
# Export to a pdf file
ggexport(res, filename = &quot;multi.page.ggplot2.pdf&quot;)
# Visualize interactively
res</code></pre>
</div>
<div>
<h2>Nested layout with ggarrange()</h2>
<p>We’ll arrange the plot created in section (@ref(mix-table-text-and-ggplot)) and (@ref(create-some-plots)).</p>
<pre><code>p1 &lt;- ggarrange(sp, bp + font(&quot;x.text&quot;, size = 9),
                ncol = 1, nrow = 2)
p2 &lt;- ggarrange(density.p, stable.p, text.p, 
                ncol = 1, nrow = 3,
                heights = c(1, 0.5, 0.3))
ggarrange(p1, p2, ncol = 2, nrow = 1)</code></pre>
<div>
<img alt="Arrange multiple ggplots on the same page" src="https://i0.wp.com/www.sthda.com/sthda/RDoc/figure/ggpubr/arrange-multiple-ggplots-nested-layout-1.png?w=450" data-recalc-dims="1">
<p>
Arrange multiple ggplots on the same page
</p>
</div>
</div>
<div>
<h2>Export plots</h2>
<p>R function: <strong>ggexport</strong>() [in ggpubr].</p>
<p>First, create a list of 4 ggplots corresponding to the variables Sepal.Length, Sepal.Width, Petal.Length and Petal.Width in the iris data set.</p>
<pre><code>plots &lt;- ggboxplot(iris, x = &quot;Species&quot;,
                   y = c(&quot;Sepal.Length&quot;, &quot;Sepal.Width&quot;, &quot;Petal.Length&quot;, &quot;Petal.Width&quot;),
                   color = &quot;Species&quot;, palette = &quot;jco&quot;
                   )
plots[[1]]  # Print the first plot
plots[[2]]  # Print the second plots and so on...</code></pre>
<p>Next, you can export individual plots to a file (pdf, eps or png) (one plot per page). It’s also possible to arrange the plots (2 plot per page) when exporting them.</p>
<p>Export individual plots to a pdf file (one plot per page):</p>
<pre><code>ggexport(plotlist = plots, filename = &quot;test.pdf&quot;)</code></pre>
<p>Arrange and export. Specify nrow and ncol to display multiple plots on the same page:</p>
<pre><code>ggexport(plotlist = plots, filename = &quot;test.pdf&quot;,
         nrow = 2, ncol = 1)</code></pre>
</div>
<div>
<h2>Acknoweledgment</h2>
<p>We sincerely thank all developers for their efforts behind the packages that ggpubr depends on, namely:</p>
<ul>
<li>Baptiste Auguie (2016). gridExtra: Miscellaneous Functions for “Grid” Graphics. R package version 2.2.1. <a rel="nofollow" href="https://cran.r-project.org/package=gridExtra" target="_blank">https://CRAN.R-project.org/package=gridExtra</a></li>
<li>Claus O. Wilke (2016). cowplot: Streamlined Plot Theme and Plot Annotations for ‘ggplot2’. R package version 0.7.0. <a rel="nofollow" href="https://cran.r-project.org/package=cowplot" target="_blank">https://CRAN.R-project.org/package=cowplot</a></li>
<li>H. Wickham. ggplot2: Elegant Graphics for Data Analysis. Springer-Verlag New York, 2009.</li>
</ul>
</div>
<div>
<h2>Infos</h2>
<p>This analysis has been performed using <strong>R software</strong> (ver. 3.3.2) and <strong>ggpubr</strong> (ver. 0.1.4.999).</p>
</div>
<p></p>

</div>
<p><br>
</p>
<p></p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page"> Easy Guides</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/RKlB1jGDOKk" height="1"></a></div>