lrony* 2009-08-08 18:16 采纳率: 0%
浏览 1835
已采纳

用 ggplot2并排绘图

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)

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

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

转载于:https://stackoverflow.com/questions/1249548/side-by-side-plots-with-ggplot2

  • 写回答

12条回答 默认 最新

  • 游.程 2010-10-14 16:52
    关注

    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)
    

    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().

    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()
    

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

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

    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.


    Appendix: Using Facets

    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)
    

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(11条)

报告相同问题?

悬赏问题

  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 如何提取csv文件中需要的列,将其整合为一篇完整文档,并进行jieba分词(语言-python)
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置