0

I have two cor.test results. I would like to visualize this 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 regression 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:)

Shawn Hemelstrand
  • 2,676
  • 4
  • 17
  • 30
  • It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick May 24 '22 at 13:49

1 Answers1

3

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

pluke
  • 3,832
  • 5
  • 45
  • 68