简体   繁体   中英

How to plot regression lines for each group separately and all groups together in one plot?

I already plot regression lines for each group separately. How to add an other regression line that combines the information of all groups?

Here are my original R script:

plotsr.sp <- ggplot(data = result.sp.melt, 
                    aes(x=belt,y=sr, group = site, color = site))+
             geom_smooth(method = "lm", se = F)+
             scale_x_discrete(labels = c("Low","Mid","High"))

Here is a sample. What I want to add is the black line in the middle.

样本图

This could be achieved by two geom_smooth layers. For the first one use the grouping variable as a local aesthetic which will give you regression lines for the groups while the second will add a regression line for the total sample:

library(ggplot2)

ggplot(data = result.sp.melt, aes(x=belt,y=sr))+
  geom_smooth(aes(group = site, color = site), method = "lm", se = F)+
  geom_smooth(method = "lm", se = F, color = "black")

Using mtcars as example data:

ggplot(data = mtcars, aes(x=hp,y=mpg))+
  geom_smooth(aes(color = factor(cyl)), method = "lm", se = F)+
  geom_smooth(method = "lm", se = F, color = "black")

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM