如何将 2 个图 (ggplot) 合并为一个图? [英] How to combine 2 plots (ggplot) into one plot?

查看:182
本文介绍了如何将 2 个图 (ggplot) 合并为一个图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过使用 R,是否可以将 2 个 ggplot 放在一起(即,在同一个图上)?我希望显示来自 2 个不同数据框的趋势,而不是将它们一个挨一个放置,我想将它们集成在一个图中,并且只更改其中一个(黑点)的颜色.

By using R, is it possible to place 2 ggplot together (i.e., on the same plot)? I wish to show a trend from 2 different data frames and instead of putting them one next to the other, I'd like to integrate them together in one plot and only to change the color of one of them (the black dot).

更具体地说,我有以下两个视觉效果:

To be more specific, I have the following 2 visuals:

ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() + geom_smooth(fill="blue", colour="darkblue", size=1)

ggplot(visual2, aes(ISSUE_DATE,COUNTED)) + geom_point() + geom_smooth(fill="red", colour="red", size=1)

它们看起来像这样(两个都有黑点,我需要将其中一个更改为不同的):

They look like this (both have black dots and I'll need to change one of them to something different):

推荐答案

用您当前的数据设置创建单个组合图看起来像这样

Creating a single combined plot with your current data set up would look something like this

p <- ggplot() +
      # blue plot
      geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
        colour="darkblue", size=1) +
      # red plot
      geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
        colour="red", size=1)

但是,如果您可以在绘图之前组合数据集,那么 ggplot 将自动给你一个图例,总的来说代码看起来更干净

however if you could combine the data sets before plotting then ggplot will automatically give you a legend, and in general the code looks a bit cleaner

visual1$group <- 1
visual2$group <- 2

visual12 <- rbind(visual1, visual2)

p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
      geom_point() +
      geom_smooth(size=1)

这篇关于如何将 2 个图 (ggplot) 合并为一个图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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