0

So I have 1 measured variabel multiple times in 4 groups of which 1 group is the refernce group where I want to make a regression plot to with the other 3 groups. How do generate that? I see lots of examples of 2 variables plotted in groups but not what I mean (like: https://community.rstudio.com/t/multiple-linear-regression-lines-in-a-graph-with-ggplot2/9328)

This my df:

df <- data.frame("Variabel" = c(1,2,3,5,6,6,3,5,8,7,4,1,3,6,8,5),
             "group" = c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4))

And her my lin regression code

 #display regression formula in plot
  my.formula <-  y ~ x 

  LM_plot <- ggplot(df, aes(x=...,y=...., shape=group, colour=group, fill=group))+
  geom_point(shape=21,size=4,colour = "black" ,alpha=0.5)+
  geom_smooth(method="lm",alpha=0.3,color="blue",fill="grey", formula = my.formula)+
  geom_abline(intercept=0,slope=1,size=0.5,linetype="dashed",color="black")+
  theme_bw(base_rect_size = 0.2) +
  labs(x = "Group 1", y = "Group 2, 3 and 4") +
  ggtitle("Title") +
  stat_poly_eq(aes(label = paste0("atop(", ..eq.label.., ",", ..rr.label.., ")")), 
               formula = my.formula, 
               parse = TRUE)
Phil
  • 7,287
  • 3
  • 36
  • 66
H. berg
  • 471
  • 1
  • 3
  • 11
  • Ive seen this solution: https://stackoverflow.com/questions/25752909/multiple-ggplot-linear-regression-lines using ggplot + geom_jitter.....+geom_jitter....+geom_jitter.....but there must be a more elegant way correct? – H. berg May 31 '21 at 13:36

1 Answers1

0

Found it:

I changed the dataframe to 4 columns, so 1 column = 1 method with its variables...

Than for each method I created a line

  LM_plot <- ggplot(testfas1, aes(x=ref method))+
  geom_point(aes(y=method 2, colour="2"), size=4,alpha=1)+
  geom_smooth(aes(y=method 2, colour="2"), method="lm",alpha=0.3,fill="black", formula = my.formula) +
  geom_point(aes(y=method 3, colour="4"), size=4 ,alpha=1)+
  geom_smooth(aes(y=method 3, colour="4"), method="lm",alpha=0.3,fill="#ff0166", formula = my.formula) +
  geom_point(aes(y=method 4, colour="6"),size=4,alpha=1)+
  geom_smooth(aes(y=method 4 colour="6"), method="lm",alpha=0.3,fill="#117f80", formula = my.formula) +
  scale_y_continuous("methods 2/3/4") +
  scale_x_continuous("refernce method 1") +
  scale_colour_manual(name="legend", values=c("black", "#ff0166", "#117f80"),
                      guide = guide_legend(override.aes = list(alpha=0, size=1)))


LM_plot + theme_prism() 

enter image description here

H. berg
  • 471
  • 1
  • 3
  • 11
  • One thing though...I tried to ditch the alpha fill in geom_smooth (the 95% confidence interval) via override.aes in the legend...however now the point is gone too...only lines appear...any clue how I can fix this?.............and i would like to add seperate formula s with LM_plot + theme_prism() .like in the beginning.... – H. berg Jun 01 '21 at 12:00