линия тренда в R в ggplot

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"), она рисует отдельно для 2-местных автомобилей, чего я не хочу.


person Dipojjal Saha    schedule 28.12.2020    source источник


Ответы (2)


Переопределите эстетику colour, которая является эстетикой группировки, с group = 1 в вызове 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)

введите здесь описание изображения

person Rui Barradas    schedule 28.12.2020

geom_smooth наследует аргументы aes от ggplot. Вы можете переместить «цвет» в geom_point или передать inherit.aes = F в 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))

введите здесь описание изображения

person mrhellmann    schedule 28.12.2020