Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return regression line for all groups in ggplot scatterplot

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))
like image 387
Danny Avatar asked Dec 19 '25 12:12

Danny


1 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

like image 65
Duck Avatar answered Dec 22 '25 02:12

Duck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!