ggplot2: Problem with x axis when adding regression line equation on each facet

后端 未结 2 1344
误落风尘
误落风尘 2020-12-11 11:24

Based on the example here Adding Regression Line Equation and R2 on graph, I am struggling to include the regression line equation for my model in each facet. However, I don

相关标签:
2条回答
  • 2020-12-11 12:09

    You can use stat_poly_eq function from the ggpmisc package.

    library(reshape2)
    library(ggplot2)
    library(ggpmisc)
    #> For news about 'ggpmisc', please, see https://www.r4photobiology.info/
    #> For on-line documentation see https://docs.r4photobiology.info/ggpmisc/
    
    df <- data.frame(year = seq(1979,2010), M02 = runif(32,-4,6), 
                     M06 = runif(32, -2.4, 5.1), M07 = runif(32, -2, 7.1))
    df <- melt(df, id = c("year"))
    
    formula1 <- y ~ x
    
    ggplot(data = df, mapping = aes(x = year, y = value)) +
      geom_point() +
      scale_x_continuous() + 
      geom_smooth(method = 'lm', se = TRUE) +
      stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~~")), 
                   label.x = "left", label.y = "top",
                   formula = formula1, parse = TRUE, size = 3) +
      facet_wrap(~ variable) 
    

    ggplot(data = df, mapping = aes(x = year, y = value)) +
      geom_point() +
      scale_x_continuous() + 
      geom_smooth(method = 'lm', se = TRUE) +
      stat_poly_eq(aes(label = paste(..eq.label.., sep = "~~~")), 
                   label.x = "left", label.y = 0.15,
                   eq.with.lhs = "italic(hat(y))~`=`~",
                   eq.x.rhs = "~italic(x)",
                   formula = formula1, parse = TRUE, size = 4) +
      stat_poly_eq(aes(label = paste(..rr.label.., sep = "~~~")), 
                   label.x = "left", label.y = "bottom",
                   formula = formula1, parse = TRUE, size = 4) +
      facet_wrap(~ variable) 
    

    Created on 2019-01-10 by the reprex package (v0.2.1.9000)

    0 讨论(0)
  • 2020-12-11 12:15

    Probably someone will suggest a better solution, but as an alternative, you can change stat_smooth_func and you can make the final row like this

    data.frame(x=1979, y=ypos, label=func_string)
    

    instead of

    data.frame(x=xpos, y=ypos, label=func_string)
    

    So, the plot will be like below

    0 讨论(0)
提交回复
热议问题