Return ggplot 散点图中所有组的回归线

Return regression line for all groups in ggplot scatterplot

我正在 ggplot 中创建一个散点图,我 class 根据公司点数确定点数。我想添加一条趋势线来显示所有点的回归。但是,当我添加 geom_smooth() 时,它会为每个 class 添加一条趋势线。我该如何修改它,以便我可以通过点的颜色显示 classes 和一条趋势线,该趋势线对所有数据点执行回归,而不管 class?

这是一些示例数据:

ff<-as.data.frame(cbind(Energy_YearsToAchieve=c(5,10,15,13,10,8),Energy_Change=c(10,12,28,25,15,10), Sector_4C=c("A","B","C","A","B","B")))



ggplot(ff, aes(x=Energy_YearsToAchieve, y=Energy_Change, color=Sector_4C)) +
  geom_point()+
  geom_smooth(method=lm, se=FALSE, fullrange=FALSE,aes(group=Sector_4C))

这可以工作但未测试,因为没有共享数据:

library(ggplot2)
#Code
ggplot(Q18a, aes(x=Energy_YearsToAchieve, y=Energy_Change, color=Sector_4C)) + 
  geom_smooth(method=lm, se=FALSE, fullrange=FALSE,aes(group=Sector_4C))+
  geom_smooth(method=lm, se=FALSE, fullrange=FALSE,aes(group=1),color='violet')

使用新数据:

#Code
ggplot(ff, aes(x=Energy_YearsToAchieve, y=Energy_Change, color=Sector_4C)) +
  geom_point()+
  geom_smooth(method=lm, se=FALSE, fullrange=FALSE,aes(group=Sector_4C))+
  geom_smooth(method = lm,se=F,aes(group=1),color='violet')

输出:

来自 OP 的以下评论:

library(ggplot2)
library(patchwork)
#Code
G1 <- ggplot(ff, aes(x=Energy_YearsToAchieve, y=Energy_Change, color=Sector_4C)) +
  geom_point()+
  geom_smooth(method=lm, se=FALSE, fullrange=FALSE,aes(group=Sector_4C))+
  ggtitle('Trend by group')
G2 <- ggplot(ff, aes(x=Energy_YearsToAchieve, y=Energy_Change, color=Sector_4C)) +
  geom_point()+
  geom_smooth(method = lm,se=F,aes(group=1),color='violet')+
  ggtitle('Trend for all data')
#Merge
G1+G2+plot_layout(guides = 'collect')

输出:

如果你想让颜色分组只用在点层,那么你需要把原来的ggplot(aes())部分的颜色映射去掉,直接放到点层。像这样:

ggplot(ff, aes(x=Energy_YearsToAchieve, y=Energy_Change)) +
  geom_point(aes(color=Sector_4C))+
  geom_smooth(method=lm, se=FALSE, fullrange=FALSE,aes(group=Sector_4C))

然后如果你想要组 的回归线和整体回归,那么你可以这样做:

ggplot(ff, aes(x=Energy_YearsToAchieve, y=Energy_Change)) +
  geom_point(aes(color=Sector_4C))+
  # individual trend lines
  geom_smooth(method=lm, se=FALSE, fullrange=FALSE,aes(color=Sector_4C))+
  # Overall trend line (no grouping or color mapping)
  geom_smooth(method=lm, se=FALSE, fullrange=FALSE))