How to combine 2 plots (ggplot) into one plot?

adhg picture adhg · Jan 17, 2014 · Viewed 141.6k times · Source

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)

and

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

enter image description here

and

enter image description here

Answer

Stuples picture Stuples · Jan 17, 2014

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)

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)