Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splitting or removing graphs after arrangeGrob

I created a graph with ggplot and later I used arrangeGrob to combine those graphs. Is there a way to remove parts a graph from this combined plot? Or maybe extract?

Here is a minimal example:

library(ggplot2)
library(gridExtra)
df <- data.frame(x=rnorm(20), y=rnorm(20), y2=rnorm(20))
g1 <- ggplot(df, aes(x, y)) + geom_point()
g2 <- ggplot(df, aes(x, y2)) + geom_point()
g <- arrangeGrob(g1,g2, widths=c(3.5,7.5), ncol=2)
print(g)

I would like to remove one of the two plots.

like image 774
drmariod Avatar asked Jun 11 '15 14:06

drmariod


People also ask

How do I put two Ggplots on top of each other?

Combine multiple ggplot on one page.Use the function ggarrange() [ggpubr package], a wrapper around the function plot_grid() [cowplot package]. Compared to plot_grid(), ggarange() can arrange multiple ggplots over multiple pages.

What does the gridExtra package allow you to do?

The gridExtra package provides useful extensions to the grid system, with an emphasis on higher-level functions to work with grid graphic objects, rather than the lower-level utilities in the grid package that are used to create and edit specific lower-level elements of a plot.

How do I arrange multiple plots 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.

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.


1 Answers

First, use grid.ls() to see a listing of the grobs that make up the plot. Here, you'll be looking for the names of the two gTree objects that encode the individual plots. (Compared to lattice, ggplot2's naming of component grobs is relatively unhelpful, although in this case, it's not too hard to see which pieces you'll want to extract.)

grid.ls()
# GRID.arrange.90
#   GRID.frame.84
#     GRID.cellGrob.85
#       GRID.frame.5
#         GRID.cellGrob.44
#           GRID.gTree.42
#             GRID.clip.43
#             layout
#         GRID.cellGrob.83
#           GRID.gTree.81
#             GRID.clip.82
#             layout
#     GRID.cellGrob.86
#       GRID.null.1
#     GRID.cellGrob.87
#       GRID.null.2
#     GRID.cellGrob.88
#       GRID.null.4
#     GRID.cellGrob.89
#       GRID.null.3

Then, you can extract and plot them like this:

gg1 <- getGrob(g, ("GRID.gTree.42"))
grid.draw(gg1)

gg2 <- getGrob(g, ("GRID.gTree.81"))
grid.draw(gg2)
like image 132
Josh O'Brien Avatar answered Nov 10 '22 07:11

Josh O'Brien