John Doe
John Doe

Reputation: 3

How to create two different regression line based on factor for each facet? R, ggplot2

I am trying to create two different lines based on exercise = 0 or exercise = 1 for each facet (by gender). The first code is without facet_wrap and the two lines based on gender are different. The second code is with facet_wrap and the two lines seem to be the same line. How can I change the code so that the two lines are different within each facet?

ggplot(cdc, aes(weight,wtdesire, color = exercise, group = 
interaction(gender,exercise))) + geom_point(alpha = 1/5) + 
geom_smooth(method = lm, aes(linetype=exercise))

produces: facet

However, when I add facet_wrap the two lines for each facet seem to be the same.

ggplot(cdc, aes(weight,wtdesire, color = exercise, group = 
interaction(gender,exercise))) + geom_point(alpha = 1/5) + 
geom_smooth(method = lm, aes(linetype=exercise)) + facet_wrap(~gender)

produces: second

Upvotes: 0

Views: 956

Answers (1)

Adam Quek
Adam Quek

Reputation: 7153

@LoBu solution is correct. Here's an example using mtcars data:

ggplot(mtcars, aes(hp, mpg, group=interaction(vs, am))) +  
       geom_point(alpha = 0.2) + 
       geom_smooth(method = lm, aes(linetype=as.factor(vs)))

enter image description here

ggplot(mtcars, aes(hp, mpg, group=vs)) +  
       geom_point(alpha = 0.5) + 
       geom_smooth(method = lm, aes(linetype=as.factor(vs))) +
       facet_wrap(~am)

enter image description here

Upvotes: 0

Related Questions