put correlation coefficient on ggplot scatter plot after faceting

Viewed 2513

I'm having issue to put correlation coefficient on my scatter plot after facet_wrap by another variable. Below is the example I made using mtcars dataset for illustration purpose. when I plot it out, both plot have the same correlation number. It seems the correlation coef is not calculated for each facet. I could not figure out a way to achieve that. Really appreciate it if anyone could kindly help with that...

library(ggplot2)
library(dplyr)
corr_eqn <- function(x,y, method='pearson', digits = 2) {
    corr_coef <- round(cor.test(x, y, method=method)$estimate, digits = digits)
    corr_pval <- tryCatch(format(cor.test(x,y, method=method)$p.value, 
                                 scientific=TRUE),
                          error=function(e) NA)
    paste(method, 'r = ', corr_coef, ',', 'pval =', corr_pval)
}

sca.plot <- function (cor.coef=TRUE) {
    df<- mtcars %>% filter(vs==1)
    p<- df %>% 
        ggplot(aes(x=hp, y=mpg))+
        geom_point()+
        geom_smooth()+
        facet_wrap(~cyl, ncol=3)

    if (cor.coef) {
        p<- p+geom_text(x=0.9*max(df$hp, na.rm=TRUE),
                        y=0.9*max(df$mpg, na.rm=TRUE),
                        label = corr_eqn(df[['hp']],df[['mpg']],
                                         method='pearson'))
    }
    return (p)    
}

sca.plot(cor.coef=TRUE)
1 Answers
Related