使用 ggplot2 并排绘图 [英] Side-by-side plots with ggplot2

查看:29
本文介绍了使用 ggplot2 并排绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 ggplot2 包并排放置两个地块,即做相当于par(mfrow=c(1,2)).

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 the following two plots show side-by-side with the same scale.

x <- rnorm(100)
eps <- rnorm(100,0,.2)
qplot(x,3*x+eps)
qplot(x,2*x+eps)

我需要将它们放在同一个 data.frame 中吗?

Do I need to put them in the same data.frame?

qplot(displ, hwy, data=mpg, facets = . ~ year) + geom_smooth()

推荐答案

任何 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.

这篇关于使用 ggplot2 并排绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆