Adding R^2 on graph with facets

后端 未结 3 506
一整个雨季
一整个雨季 2020-12-29 12:06

I am plotting geom_points on multiple facets and would like to annotate R^2 on each facet (preferably on the facet_label rather on the graph.) I have found some code here wh

3条回答
  •  误落风尘
    2020-12-29 12:42

    Here is a complete solution including insertion of the R^2 value into the facet labels, otherwise built upon the solution from Sven Hohenstein.

    First, change the function for getting the R^2 values so that it only grabs the number without any extra text

    lm_eqn = function(df){
      m = lm(ln_x ~ ln_y, df);
      eq <- substitute(r2, 
                       list(r2 = format(summary(m)$r.squared, digits = 3)))
      as.character(as.expression(eq));                 
    }
    

    put equations for each roi_size into a dataframe (as with Sven's solution),

    eqns <- by(df, df$roi_size, lm_eqn)
    df2 <- data.frame(eq = unclass(eqns), roi_size = as.numeric(names(eqns)))
    

    but then concatenate them with the roi_size in a new column

    df2$lab = paste("roi_size =", df2$roi_size, "R^2 =", df2$eq, sep=" ")
    

    make a labeling function that will refer to your data frame of labels

    r2_labeller <- function(variable,value){
      return(df2$lab)
    }
    

    then plot, using the labeling function while calling facet_wrap

    ggplot(df, aes(x=ln_x, y=ln_y)) +
      geom_point(shape=19, aes(colour=factor(depth))) + 
      geom_smooth(method="lm") + 
      facet_wrap(~roi_size, labeller = r2_labeller) + 
      scale_color_discrete("depth (mm)") +
      labs(y=expression(ln(frac(C[low]^air,C[low]^depth))),
               x=expression(ln(frac(C[low]^depth,C[high]^depth))) ) +
      theme(axis.title.x = element_text(colour='blue', size=16, hjust=0.9)) + 
      theme(axis.title.y = element_text(colour='blue', size=16, angle=0))
    

提交回复
热议问题