Home > database >  How to stagger the equation of line Rsquared for multiple factors on a R ggplot?
How to stagger the equation of line Rsquared for multiple factors on a R ggplot?

Time:06-09

I have four factors each with it's unique regression line and Rsquared. I want to do three things:

  1. Place the Rsq in line with the equation of the line (currently its at the bottom)

  2. Arrange the four equations on seperate lines

  3. Arrange the four equations on the top, right.

     set.seed(111)
     var <- rep(c("SP1","SP2","AB1","AB2"), times = 5)
     var.val <- rnorm(20,5,1)
     level <- rep(c(100,200,300,400), each = 5)
    
     df <- data.frame(var, var.val, level)
    
       df <- df[order(-level),]
    
       ggplot(df, aes(x = level, y = var.val, col = var, group = var, linetype = var))   
       geom_point(aes(fill = var), colour="white",pch=21, size=4, stroke = 1,
                  alpha = 0.7, data = df[df$var %in% c("SP1", "SP2"),])  
       theme_classic()   
       geom_smooth(data = df[df$var %in% c("SP1", "SP2"),],
                   method = "lm", formula = y ~ x, alpha = 0.2)  
       geom_smooth(data = df[!df$var %in% c("SP1", "SP2"),],
                   method = "lm", formula = y ~ x, se = FALSE)    
       scale_linetype_manual(values = c("dotdash", "dashed","solid", "solid"))   
       scale_colour_manual(values = c("black","black","red","blue"))   
       stat_poly_eq(formula = y ~ x, aes(label = paste("atop(", ..eq.label.., ",", ..rr.label.., ")")), label.y = 0.9, parse = TRUE, size = 3)
    

    enter image description here

CodePudding user response:

The atop() function creates a line break between two equations. You can use list() instead.

For right top alignment, you can give values in decimals as a sequence as below. Each equation needs different values, so that there is no overlap.

ggplot(df, aes(x = level, y = var.val, col = var, group = var, linetype = var))   
  geom_point(aes(fill = var), colour="white",pch=21, size=4, stroke = 1,
             alpha = 0.7, data = df[df$var %in% c("SP1", "SP2"),])  
  theme_classic()   
  geom_smooth(data = df[df$var %in% c("SP1", "SP2"),],
              method = "lm", formula = y ~ x, alpha = 0.2)  
  geom_smooth(data = df[!df$var %in% c("SP1", "SP2"),],
              method = "lm", formula = y ~ x, se = FALSE)    
  scale_linetype_manual(values = c("dotdash", "dashed","solid", "solid"))   
  scale_colour_manual(values = c("black","black","red","blue"))   
  stat_poly_eq(formula = y ~ x, aes(label = paste("list(", ..eq.label.., ",", ..rr.label.., ")")), 
               label.x = 0.9,
               label.y = seq(0.85, 1, by =0.05), parse = TRUE, size = 3)

enter image description here

  • Related