Search code examples
rggplot2linear-regression

How can I plot two linear regressions on one same graph?


I used stat_poly_eq to plot the linear regression equation for the dataset of two years. Now I want to draw the two equations in the same graph.

Here is the original dataset:

df<-structure(list(Year = c(2017, 2017, 2017, 2017, 2017, 2017, 2021, 
2021, 2021, 2021, 2021, 2021), Variety = c("Sultana - MG 000", 
"ES Pallador - MG I", "Isidor - MG I", "Santana - MG I/II", "Blancas - MG II", 
"Ecudor - MG II", "Sultana - MG 000", "ES Pallador - MG I", "Isidor - MG I", 
"Santana - MG I/II", "Blancas - MG II", "Ecudor - MG II"), FTSWt = c(0.91, 
0.79, 0.92, 0.48, 0.51, 0.46, 0.93, 0.59, 0.58, 0.44, 0.48, 0.52
), SLA = c(85.38, 111.94, 108.56, 120.54, 130.14, 123.25, 109.05, 
149.97, 168.64, 162.96, 140.18, 175.1)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -12L))

Here is my original data:

library(ggplot2)
library(readxl)
library("RColorBrewer")
library(stats)
library(ggpmisc)

ggplot(df,aes(y=FTSWt,x=SLA))+
geom_point(aes(color= Variety),size=3)+
geom_smooth(method = "lm", formula = y ~ x,se=FALSE,color="black") +
stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")), 
               label.x.npc = "right", label.y.npc = 0.85,
               formula = y ~ x, parse = TRUE, size = 4)+
geom_text_repel(aes(label=Variety,color=Variety))+
scale_color_manual(values = c("#E41A1C", "#377EB8", "#4DAF4A", "#984EA3","#FF7F00","#A65628","#A65628"))+
labs(y = "SLA", x = "FTSWt")+
theme_bw() + 
theme(panel.grid=element_blank(),
        axis.text.x = element_text(size=12,vjust=0.5),
        axis.text.y = element_text(size=12),
        axis.title.x = element_text(size = 12),
        axis.title.y = element_text(size = 12),
        legend.title=element_text(size=13),
        legend.text=element_text(size=11),
        legend.position = "none")+
facet_wrap(~Year)

Here is the graph that I got: enter image description here

Now I want to combine these two graphs into one graph. Two types of lines with two corresponding equations (distinguished by color).

Any suggestions are welcome! Thank you in adavance!


Solution

  • you can set the group aesthetic and proceed as intended like so:

    ggplot(aes(FTSWt, SLA, group = Year)) +
       ## rest of ggplot stuff
    

    (don't forget to remove the trailing facet_wrap)