分面后将相关系数放在 ggplot 散点图上

zes*_*sla 5 r ggplot2

我在 facet_wrap 之后通过另一个变量将相关系数放在散点图上时遇到问题。下面是我使用 mtcars 数据集制作的示例,用于说明目的。当我绘制出来时,两个图都有相同的相关数。似乎没有为每个方面计算相关系数。我想不出实现这一目标的方法。如果有人可以帮助解决这个问题,真的很感激......

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)
Run Code Online (Sandbox Code Playgroud)

PoG*_*bas 5

通过 variable 调用 facets inputFacet,循环这个变量以corr_enq使用变量名和get.

在闪亮中,您可能会有用户输入,因为input$facet这里称为inputFacet. 我们绘制主图以获取这个变量facet_wrap(~ get(inputFacet), ncol = 3)。接下来,我们使用 循环遍历所有方面选项for(i in seq_along(resCor$facets))并将结果存储在 中rescore

这应该可以解决“未为每个方面计算相关系数”的问题。

library(dplyr)
library(ggplot2)

inputFacet <- "cyl"
cor.coef = TRUE
df <- mtcars

p <- df %>% 
    ggplot(aes(hp, mpg))+
    geom_point()+
    geom_smooth()+
    facet_wrap(~ get(inputFacet), ncol = 3)

if (cor.coef) {

    resCor <- data.frame(facets = unique(mtcars[, inputFacet]))
    for(i in seq_along(resCor$facets)) {
        foo <- mtcars[mtcars[, inputFacet] == resCor$facets[i], ]
        resCor$text[i] <- corr_eqn(foo$hp, foo$mpg)
    }
    colnames(resCor)[1] <- inputFacet

    p <- p + geom_text(data = resCor, 
                       aes(0.9 * max(df$hp, na.rm = TRUE),
                           0.9 * max(df$mpg, na.rm = TRUE),
                           label = text))

}

p
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明