'Two regression lines in one plot?

I have two cor.test I would like to visualize in a plot using geom_smooth. So far I have a working code with one regression line but I don't know how to add a second regressions line to the same plot. This is my code so far:

cor(opg6wave1$godimportant, opg6wave1$aj, use = 'complete.obs')#-0.309117
cor(opg6wave6$godimportant, opg6wave6$aj, use = 'complete.obs') ##=-0.4321519

ggplot(opg6wave1, aes(x= godimportant, y= aj))+ 
geom_smooth()+ 
labs(title = "Religion og abort over tid", x='Religiøsitet', y= 'Holdning til abort')+
theme_classic()

Thank y'all:)



Solution 1:[1]

I don't have access to your dataset, you might want to share it? I'm using the diamonds dataset from tidyverse. By putting the dataset in the ggplot(...) command you then have it transfer to any underlying geom_.... You want to specify the data for each regression line separately. We can have two geom_smooth() by specifying the data for each of them separately.

library(tidyverse)

ggplot()+ 
  geom_smooth(diamonds %>% filter(color=="E"), 
              mapping=aes(x=depth, y=price))+
  geom_smooth(diamonds %>% filter(color=="J"), 
              mapping=aes(x=depth, y=price)) +
  theme_classic()

enter image description here

The above for linear model smooth:

ggplot()+ 
  geom_smooth(diamonds %>% filter(color=="E"), 
              mapping=aes(x=depth, y=price),
              method=lm)+
  geom_smooth(diamonds %>% filter(color=="J"), 
              mapping=aes(x=depth, y=price),
              method=lm) +
  theme_classic()

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pluke