Side-by-side plots with ggplot2

后端 未结 13 2465
轮回少年
轮回少年 2020-11-22 02:06

I would like to place two plots side by side using the ggplot2 package, i.e. do the equivalent of par(mfrow=c(1,2)).

For example, I would like to have t

13条回答
  •  情深已故
    2020-11-22 02:25

    ggplot2 is based on grid graphics, which provide a different system for arranging plots on a page. The par(mfrow...) command doesn't have a direct equivalent, as grid objects (called grobs) aren't necessarily drawn immediately, but can be stored and manipulated as regular R objects before being converted to a graphical output. This enables greater flexibility than the draw this now model of base graphics, but the strategy is necessarily a little different.

    I wrote grid.arrange() to provide a simple interface as close as possible to par(mfrow). In its simplest form, the code would look like:

    library(ggplot2)
    x <- rnorm(100)
    eps <- rnorm(100,0,.2)
    p1 <- qplot(x,3*x+eps)
    p2 <- qplot(x,2*x+eps)
    
    library(gridExtra)
    grid.arrange(p1, p2, ncol = 2)
    

    More options are detailed in this vignette.

    One common complaint is that plots aren't necessarily aligned e.g. when they have axis labels of different size, but this is by design: grid.arrange makes no attempt to special-case ggplot2 objects, and treats them equally to other grobs (lattice plots, for instance). It merely places grobs in a rectangular layout.

    For the special case of ggplot2 objects, I wrote another function, ggarrange, with a similar interface, which attempts to align plot panels (including facetted plots) and tries to respect the aspect ratios when defined by the user.

    library(egg)
    ggarrange(p1, p2, ncol = 2)
    

    Both functions are compatible with ggsave(). For a general overview of the different options, and some historical context, this vignette offers additional information.

提交回复
热议问题