ggplot中R中的趋势线

ggplot中R中的趋势线,r,trendline,R,Trendline,为此,我试图添加一条适用于所有类别的趋势线,因为如果我添加一条趋势线geom_smooth(method=“lm”),它会分别为双座车绘制,我不希望它覆盖颜色美学,这是分组美学,在调用geom_smooth时使用group=1 mpg %>% mutate(Color=ifelse(class=='2seater','2seater','Other')) %>% ggplot(aes(displ, hwy, colour = Color)) + geom_point

为此,我试图添加一条适用于所有类别的趋势线,因为如果我添加一条趋势线
geom_smooth(method=“lm”)
,它会分别为双座车绘制,我不希望它覆盖
颜色
美学,这是分组美学,在调用
geom_smooth
时使用
group=1

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"))

几何平滑继承了ggplot的
aes
参数。您可以将“color”移动到geom_点,或将
inherit.aes=F
传递到geom_平滑

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)

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