Return regression line for all groups in ggplot scatterplot

Viewed 789

I'm creating a scatterplot in ggplot where I am classifying the points based on company point. I would like to add a single trend line which shows the regression of all points. However, when I add geom_smooth() it adds a trend line for each class. How can I modify this so that I can show both the classes via the colors of the points and a single trend line that performs a regression of all data points regardless of class?

enter image description here

Here is some sample data:

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

This can work but not tested as no data was shared:

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

Using new data:

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

Output:

enter image description here

Following comments from 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')

Output:

enter image description here

If you want the color grouping to only be used in the point layer, then you need to remove the color mapping from the original ggplot(aes()) part and just put it in the point layer. Like this:

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

And then if you want regression lines for the groups and and overall regression, then you do it like this:

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