且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 ggplot2 并排绘图

更新时间:2022-04-19 01:22:31

任何 ggplots 并排(或网格上的 n 个图)

gridExtra 包将合并多个图;这就是你将两个并排放置的方式.

Any ggplots side-by-side (or n plots on a grid)

The function grid.arrange() in the gridExtra package will combine multiple plots; this is how you put two side by side.

require(gridExtra)
plot1 <- qplot(1)
plot2 <- qplot(1)
grid.arrange(plot1, plot2, ncol=2)

当两个图不是基于相同的数据时,这很有用,例如,如果您想在不使用 reshape() 的情况下绘制不同的变量.

This is useful when the two plots are not based on the same data, for example if you want to plot different variables without using reshape().

这会将输出绘制为副作用.要将副作用打印到文件,请指定设备驱动程序(例如 pdfpng 等),例如

This will plot the output as a side effect. To print the side effect to a file, specify a device driver (such as pdf, png, etc), e.g.

pdf("foo.pdf")
grid.arrange(plot1, plot2)
dev.off()

或者,将 arrangeGrob()ggsave() 结合使用,

or, use arrangeGrob() in combination with ggsave(),

ggsave("foo.pdf", arrangeGrob(plot1, plot2))

这相当于使用 par(mfrow = c(1,2)) 制作两个不同的图.这不仅可以节省整理数据的时间,而且当您需要两个不同的图时,这也是必要的.

This is the equivalent of making two distinct plots using par(mfrow = c(1,2)). This not only saves time arranging data, it is necessary when you want two dissimilar plots.

分面有助于为不同的组制作相似的图.下面的许多答案中都指出了这一点,但我想用与上述图等效的示例来强调这种方法.

Facets are helpful for making similar plots for different groups. This is pointed out below in many answers below, but I want to highlight this approach with examples equivalent to the above plots.

mydata <- data.frame(myGroup = c('a', 'b'), myX = c(1,1))

qplot(data = mydata, 
    x = myX, 
    facets = ~myGroup)

ggplot(data = mydata) + 
    geom_bar(aes(myX)) + 
    facet_wrap(~myGroup)

更新

plot_grid函数>cowplot 作为 grid.arrange 的替代品值得一试.请参阅下面@claus-wilke 的答案此小插图 用于等效方法;但该函数允许根据此小插图对绘图位置和大小进行更精细的控制.


Update

the plot_grid function in the cowplot is worth checking out as an alternative to grid.arrange. See the answer by @claus-wilke below and this vignette for an equivalent approach; but the function allows finer controls on plot location and size, based on this vignette.