Multiple regression lines in ggplot

Hi guys! Really struggling with this one and it feels like a small mistake but can't figure it out.
I'm using the geom_smooth function for the regression line, but I need 2 regression lines (one for each species). If I use geom_smooth I simply get one regression line. How to I get multiple lines on the scatterplot?
Thanks in advance!

head(TempDeltamass, 10)[, c('Temp', 'Mass', 'Species')]
datapasta::df_paste(head(TempDeltamass, 10)[, c('Temp', 'Mass', 'Species')])
data.frame(
stringsAsFactors = FALSE,
Temp = c(37.9,31.4,31.4,31.4,31.4,
38.4,34.1,34.1,34.1,34.1),
Mass = c(0.600280131,4.412614474,
-2.152466368,4.278946564,3.144654088,0,14.18475774,
-10.69798402,8.349819224,-5.364835939),
Species = c("AGH","SYH","SYH","SYH",
"SYH","AGH","SYH","SYH","SYH","SYH")
)
library(ggplot2)
ggplot(TempDeltamass, aes(x = Temp, y = Mass))+
geom_point(aes(color = factor(Species)), size = 2) + geom_smooth(method = "lm", fill = NA)
pointcol <- ggplot(TempDeltamass, aes(x = Temp, y = Mass))+
geom_point(aes(color = factor(Species)), size = 2)
pointcol + scale_color_manual(values = c("grey20", "orange", "red"))
TempDeltamass <- pointcol + scale_color_manual(values = c("grey20", "orange", "red"))
TempDeltamass + labs(x = 'Temperature (°C)', y = 'Diurnal body mass change (%)', color = 'Species')
TempDeltamass + scale_y_continuous(breaks = seq(-50, 100, by = 10)) + labs(x = 'Temperature (°C)', y = 'Diurnal body mass change (%)', color = 'Species') + theme_classic()
regline <- TempDeltamass + scale_y_continuous(breaks = seq(-50, 100, by = 10)) + labs(x = 'Temperature (°C)', y = 'Diurnal body mass change (%)', color = 'Species') + theme_classic()
regline + geom_smooth(method = "lm", fill = NA)

Hi,

There are always different ways of approaching this requirement, one way would be as follows:

library(tidyverse)
iris %>% 
  ggplot(aes(Sepal.Length, Sepal.Width, color = Species, group = Species)) +
  geom_point() +
  geom_smooth(method = "lm") +
  facet_wrap(~ Species) +
  theme(legend.position = "none")
#> `geom_smooth()` using formula 'y ~ x'

Created on 2021-02-09 by the reprex package (v1.0.0)

If you don't like the split into 3 separate graphs, then you can easily comment/remove the facet_wrap() line.

HTH
lars

Wonderful! Thank you so much. This really helped!

You're welcome.

BTW, please note that the group = Species can safely be removed from the aes() as the grouping is already taken care for by using the color aesthetic. So, this works just as fine:

iris %>% 
  ggplot(aes(Sepal.Length, Sepal.Width, color = Species)) +
  geom_point() +
  geom_smooth(method = "lm") +
  facet_wrap(~ Species) +
  theme(legend.position = "none")

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.