trendline in R in ggplot

Viewed 35
mpg %>% 
  mutate(Color=ifelse(class=='2seater','2seater','Other')) %>% 
  ggplot(aes(displ, hwy, colour = Color)) + 
  geom_point() + 
  scale_color_manual(values = c("2seater" = "#992399", "Other" = "#000000"))

To this I am trying to add a trend line which is for all categories because , if I add a trend line geom_smooth(method="lm"), it draws for 2 seater separately which I don't want

2 Answers

Override the colour aesthetic, which is the grouping aesthetic, with group = 1 in the call to geom_smooth.

library(tidyverse)

mpg %>% 
  mutate(Color=ifelse(class=='2seater','2seater','Other')) %>% 
  ggplot(aes(displ, hwy, colour = Color)) + 
  geom_point() + 
  scale_color_manual(values = c("2seater" = "#992399", "Other" = "#000000")) +
  geom_smooth(aes(group = 1),
              method = "lm", formula = y ~ x)

enter image description here

The geom_smooth inherits the aes arguments from ggplot. You can move 'colour' to geom_point, or pass inherit.aes = F to geom_smooth.

mpg %>% 
  mutate(Color=ifelse(class=='2seater','2seater','Other')) %>% 
  ggplot(aes(displ, hwy)) + 
  geom_point(aes(, colour = Color)) + 
  scale_color_manual(values = c("2seater" = "#992399", "Other" = "#000000"))  + geom_smooth(method = 'lm')

#or:
mpg %>% 
  mutate(Color=ifelse(class=='2seater','2seater','Other')) %>% 
  ggplot(aes(displ, hwy, colour = Color)) + 
  geom_point() + 
  scale_color_manual(values = c("2seater" = "#992399", "Other" = "#000000")) + geom_smooth(method = 'lm', inherit.aes = F, aes(displ, hwy))

enter image description here

Related