geom_smooth by group AND without grouping in one plot

I'm interested in putting both a linear regression line through each group of data points AND an overall linear regression line through the whole dataset (to show the importance of including an interaction term). I'm having trouble finding an example, however, as it seems ggplot can't do both in the same plot.

library(ggplot2)

data(iris)

# How would I combine these two geom_smooth(s) into one plot?
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, color=Species)) + 
  geom_point() + 
  geom_smooth(method="lm")

ggplot(iris, aes(x=Petal.Width, y=Petal.Length)) + 
  geom_point() + 
  geom_smooth(method="lm")

  #... + geom_smooth(method = "lm", color=Sex) + didn't work

Does this work for you?

ggplot(data = iris, aes(x=Petal.Width, y = Petal.Length)) + 
  geom_point(aes(color = Species)) +
  geom_smooth(aes(color = Species), method = "lm") +
  geom_smooth(method = "lm", color = "black")
1 Like

Works perfectly, thank you!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.