Gonzalo de Quesada
Gonzalo de Quesada

Reputation: 315

How to add a smooth line using ggplot2 in a plot with 2 different datasets

I am trying to make a scatter plot with 2 different datasets and a smooth line of each scatter to compare them.

I can do it separately but for some reason, I can not do it when both are in the same plot (I know it might be my lack of coding knowledge)

I am trying this maybe someone can point my mistake

df1 <- data.frame("x1"=1:25, "y1"=rnorm(25))
df2 <- data.frame("x2"=1:25, "y2"=rnorm(25))
ggplot()+geom_point(data=df1,aes(x=x1,y=y1),size=2,shape=23,color="blue")+
  geom_point(data=df2,aes(x=x2,y=y2),size=2,shape=23,color="red")+geom_smooth(se=F)

Thanks for all the help

Edit: I added workable data as suggested

Upvotes: 1

Views: 2511

Answers (1)

stefan
stefan

Reputation: 125727

It's basically the same as for the other geoms. Pass each dataframe to a separate geom_smooth and define the mapping or the aesthetics:

library(ggplot2)
set.seed(42)
df1 <- data.frame("x1"=1:25, "y1"=rnorm(25))
df2 <- data.frame("x2"=1:25, "y2"=rnorm(25))
ggplot()+
  geom_point(data=df1,aes(x=x1,y=y1),size=2,shape=23,color="blue")+
  geom_point(data=df2,aes(x=x2,y=y2),size=2,shape=23,color="red")+
  geom_smooth(data=df1,aes(x=x1,y=y1), se=F) +
  geom_smooth(data=df2,aes(x=x2,y=y2), se=F)
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Upvotes: 3

Related Questions