Add ggplot regression line for specific groups only

I want to add trendlines to my ggplot, but only for meaningful relationships. Now geom_smootheither stat_smoothadds trend lines for each group, but I want to indicate which groups receive the trend line and which do not.

Below is an example of my script:

plot20<-ggplot(data, aes(x=data$Density, y=data$Total.degrees, color=Species, shape=Species)) 
+ geom_point(size=3) 
+ scale_shape_manual(values=shapeset) 
+ scale_colour_manual(values=colorset) 
+ theme(legend.position="none") 
+ geom_smooth(method=lm, se=FALSE) 
+5
source share
1 answer

One solution would be to place subset()your data inside geom_smooth()and indicate the value for which you need to build a trend line.

Data was used as an example mtcars(since no example data was provided). If the value is subset() cylselected, values ​​4 or 6. Insede should geom_smooth()also aes()be repeated.

ggplot(mtcars,aes(wt,mpg,color=factor(cyl)))+geom_point()+
    geom_smooth(data=subset(mtcars,cyl==4 | cyl==6),
               aes(wt,mpg,color=factor(cyl)),method=lm,se=FALSE)

enter image description here

+11
source

All Articles