3

I have two data frames similar to these:

date <- c("2014-07-06", "2014-07-06","2014-07-06","2014-07-07", "2014-07-07","2014-07-07","2014-07-08","2014-07-08","2014-07-08")
TIME <- c("01:01:01", "10:02:02", "18:03:03","01:01:01", "10:02:02", "18:03:03","01:01:01", "10:02:02", "18:03:03")
depth <- c(12, 23, 4, 15, 22, 34, 22, 12, 5)
temp <- c(14, 10, 16, 13, 10, 9, 10, 14, 16)
depth.temp <- data.frame(date, TIME, depth, temp)
depth.temp$asDate<-as.Date(depth.temp$date)

date <- c("2014-07-06", "2014-07-07","2014-07-08") 
meandepth <- c(13, 16, 9) 
cv <- c(25, 9, 20) 
depth.cv <- data.frame(date, meandepth, cv)
depth.cv$asDate<-as.Date(depth.cv$date)

from the first one I have created following plot:

library(ggplot2)
p1 <- qplot(asDate, depth, data=depth.temp, colour=temp, size = I(5), alpha = I(0.3))+ scale_y_reverse()
p1 + scale_colour_gradientn(colours = rev(rainbow(12)))

And from the second one this plot:

p2 <- ggplot(depth.cv, aes(x=asDate, y=meandepth))+ scale_y_reverse()
p2 + geom_line(aes(size = cv))

I want to merge both graphs into one with the points in the back and the line in the front, any suggestions? Note that the points and the line are NOT derived from the same data but from two different data frames.

Johan Leander
  • 70
  • 1
  • 1
  • 7
  • possible duplicate of [How to combine 2 plots (ggplot) into one plot?](http://stackoverflow.com/questions/21192002/how-to-combine-2-plots-ggplot-into-one-plot) – figurine Apr 22 '15 at 11:18
  • It is similar but in that question both points and line are created from the same data frame whereas I use two seperate data frames for the points and the line – Johan Leander Apr 22 '15 at 11:56
  • Arrange your code in similar structure to the linked answer and make sure to define which data frame is used for each plot and it'll work fine. – figurine Apr 22 '15 at 12:01

2 Answers2

7

You can add data to any geom_ independent of what you use in the main ggplot call. For this, I'd skip any data or aesthetic mapping assignments in the main ggplot call and do them all in each respective geom_:

library(scales)

gg <- ggplot()
gg <- gg + geom_point(data=depth.temp, aes(x=asDate, y=depth, color=temp), size=5, alpha=0.3)
gg <- gg + geom_line(data=depth.cv, aes(x=asDate, y=meandepth, size=cv))
gg <- gg + scale_color_gradientn(colours=rev(rainbow(12)))
gg <- gg + scale_x_date(labels=date_format("%Y-%m-%d"))
gg <- gg + scale_y_reverse()
gg <- gg + labs(x=NULL, y="Depth")
gg <- gg + theme_bw()
gg

enter image description here

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
2

In my case, for the line plot to show I had to set aes like:

aes(x=asDate, y=meandepth, group=1)

in the geom_line plot

Picarus
  • 760
  • 1
  • 10
  • 25