Adding R^2 on graph with facets

后端 未结 3 468
一整个雨季
一整个雨季 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:34

    The following seems to work

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

    Create new data frame containing R^2 for each roi_size

    labeldata <- ddply(df,.(roi_size),lm_eqn )
    

    and geom_text becomes

    geom_text(data=labeldata,aes(x=1.5,y=2.2,label=eq,family="serif"), color='blue',  parse=TRUE)
    
    0 讨论(0)
  • 2020-12-29 12:42

    You can create a new data frame containing the equations for the levels of roi_size. Here, by is used:

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

    Now, this data frame can be used for the geom_text function:

    geom_text(data = df2, aes(x = 1.5, y = 2.2, label = eq, family = "serif"), 
              color = 'blue',  parse = TRUE)
    

    enter image description here

    0 讨论(0)
  • 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))
    

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