user6750230 user6750230 - 2 months ago 8
R Question

Overlaying two/more graphs using R

I have been referring stackoverflow posts and came up with query over a gglot2 features.

The data set used for code is as follows.

TimeStamp data_1 data_2 data_3
15:11:37.474 99.791028 0.312498 99.47853
15:16:22.373 99.791028 0.729162 99.061866
15:21:37.424 99.791028 0.104166 99.686862
15:31:52.475 88.02027 90.520254
15:42:07.157 99.99936 0.208332 99.791028
15:43:22.279 99.99936 0.52083 99.47853
15:45:37.673 99.686862 0 99.686862
15:52:52.872 99.686862 0.729162 98.9577

p1<- ggplot(df, aes(TimeStamp, data_1,group=1)) + geom_point() + geom_point(data = df[df$data_1 > 80,], pch = 21, fill = NA, size = 4, colour = "red", stroke = 1) + geom_line()
p2<-ggplot(df, aes(TimeStamp, data_3,group=1)) + geom_point() + geom_point(data = df[df$data_3 > 70,], pch = 21, fill = NA, size = 4, colour = "blue", stroke = 1) + geom_line()


I am trying to overlay P1 and P2 into same X and Y axis using
print(p1+p2).

But, came up with below error.

Error in p + o : non-numeric argument to binary operator
In addition: Warning message:
Incompatible methods ("+.gg", "Ops.data.frame") for "+"


what these graphs will do is; it will circle certain data points based on conditions and display two graphs in same region.

Answer

Try this

p1<- ggplot(df, aes(TimeStamp, data_1,group=1)) + geom_point(pch = 21, fill = NA, size = 4, colour = "red", stroke = 1)+geom_point()+geom_line(colour = "red")
p2 <- p1+geom_line(data=df, aes(TimeStamp, data_3),colour="blue")+
  geom_point(data=df, aes(TimeStamp, data_3,group=data_3),colour="blue",pch = 21, size = 4, stroke = 1,fill= NA)+geom_point(data=df, aes(TimeStamp, data_3,group=data_3))


print(p2)

enter image description here

Comments