Is it possible to generate a single geom_smooth line if I have dots by color?

I am trying to create a simple XY scatterplot where each data point is colored based on a categorical variable. I want to add a single regression line for all the dots into a single model, but I cannot figure out how to do it since the code below shows one per category. I don't see an obvious argument to change this in geom_smooth. Any ideas? Thank you!

ggplot(mpg, aes(displ, hwy, colour = class)) +
  geom_point() +
  geom_smooth(se = FALSE, method = glm)

Hi @brainiac,
Welcome to the RStudio Community Forum.

Does this do what you want?

ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(colour = class)) +
geom_smooth(se = FALSE, method = glm)

Yes, that's exactly it. Thank you. I guess if you bring color through ggplot all subsequent layers are applied per factor? Thanks again

As I understand the situation, the geoms generally have an argument named inherit.aes with a default value of TRUE. Any settings in the default aes set in ggplot() will be shared in the geom. If you set inherit.aes to FALSE, the geom's aes will be entirely independent.

geom_point(
  mapping = NULL,
  data = NULL,
  stat = "identity",
  position = "identity",
  ...,
  na.rm = FALSE,
  show.legend = NA,
  inherit.aes = TRUE
)

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.