Search code examples
rggplot2regressiondplyrggvis

multiple layer smoothed plots using qplot


here is the sample data-set of the plot that i have tried

x<-runif(3, min=4, max=50)
y<-runif(6, min=3, max=14)

x1 <-runif(8, min=7, max=52)
y1 <-runif(5, min=5, max=18)

i can plot smooth line using the following code.

qplot(y,x, geom='smooth', span =0.05)
qplot(y1, x1, geom='smooth', span =0.05)

but they are plotted in two separate plots; how can i plot both the smooth lines on a same plot on different layers?


Solution

  • You have some problems with your example as pointed out in the comments

    set.seed(1)
    x <- sort(runif(20, min=4, max=50))
    y <- sort(runif(20, min=3, max=14))
    
    x1 <-sort(runif(20, min=7, max=52))
    y1 <-sort(runif(20, min=5, max=18))
    

    You can use qplot and string a bunch of layers together

    library(ggplot2)
    qplot(x, y) + geom_smooth(aes(x, y)) + geom_point(aes(x1, y1)) + geom_smooth(aes(x1, y1))
    

    enter image description here

    But it is easier to use ggplot once you have the data in the proper format

    dd <- data.frame(x, x1, y, y1)
    ll <- reshape(dd, dir = 'long', varying = list(1:2, 3:4))
    
    ggplot(ll, aes(x, y, group = time)) + geom_point() + geom_smooth()