2017-09-15 93 views
2

我在使用另一個變量facet_wrap後在散點圖上放置相關係數的問題。 下面是我使用mtcars數據集進行說明的例子。當我繪製出來時,兩個圖都有相同的相關數。似乎沒有爲每個方面計算相關係數。我無法想出一個辦法來實現這一點。真的很感激,如果有人能好心提供幫助的......通過可變inputFacet在分面後在ggplot散點圖上加上相關係數

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) 
+0

我不會那樣做的......每個函數一個功能。使用'ggplot2'繪製你的數據,使用'cor'來計算相關性,不要混合這些東西。使用base R來計算每個'cyl'和管道到'geom_text'的相關性。 – PoGibas

+0

@PoGibas我只是用mtcars作爲例子。在我的工作中,我需要爲有光澤的應用可視化目的做到這一點。選擇facet_wrap變量並繪製帶有相關係數的散點圖。 – zesla

+0

如果我的解決方案有助於解決您的問題,您可以接受答案,以便我們可以關閉該問題:) – PoGibas

回答

1

通話方面,遍歷這個變量使用變量名來計算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 

enter image description here