Brodo_Swaggins
Brodo_Swaggins

Reputation: 13

Two regression lines in one plot?

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:)

Upvotes: 0

Views: 693

Answers (1)

pluke
pluke

Reputation: 4356

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

Upvotes: 3

Related Questions