ggplot中R中的趋势线

问题描述

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 个我不想要的座位绘制

解决方法

在对 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)

enter image description here

,

geom_smooth 继承了 ggplot 的 aes 参数。您可以将“颜色”移至 geom_point,或将 inherit.aes = F 传递至 geom_smooth。

mpg %>% 
  mutate(Color=ifelse(class=='2seater',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',"Other" = "#000000")) + geom_smooth(method = 'lm',inherit.aes = F,aes(displ,hwy))

enter image description here