2017-08-25 183 views
3

我的問題是雙重的;ggpairs與相關值的熱圖繪圖

我有一個ggpairs陰謀與默認upper = list(continuous = cor),我想通過相關值對瓷磚着色(完全像ggcorr所做的那樣)。

我有這樣的:ggpairs plot of daily flows
我想情節上面進行着色這樣的相關值:ggcorr heatmap of correlation values

library(GGally) 

sample_df <- data.frame(replicate(7,sample(0:5000,100))) 
colnames(sample_df) <- c("KUM", "MHP", "WEB", "OSH", "JAC", "WSW", "gaugings") 

ggpairs(sample_df, lower = list(continuous = "smooth")) 
ggcorr(sample_df, label = TRUE, label_round = 2) 

我有過短暫的旅途中,在試圖用upper = list(continuous = wrap(ggcorr)但沒有任何運氣,並且,鑑於這兩個函數都會返回劇情調用,我不認爲這是正確的道路?

我知道我可以在ggplot建立這一目的(例如Sandy Muspratt's solution),但鑑於GGally包已經有我找的,我想我可能會被忽視的東西的功能。


更廣泛地說,我想知道我們或者如果我們可以調用相關值?一個更簡單的辦法可能是顏色標籤,而不是區塊(即this question使用顏色,而不是大小),但我需要一個變量分配給顏色...

下能夠調用的相關值在其他地塊使用會很方便,但我想我可以自己重新計算它們。

謝謝!

回答

4

一種可能的解決方案是從ggcorr相關矩陣積得到的顏色的列表,並設置這些顏色作爲ggpairs矩陣地塊的上部圖塊背景。

library(GGally) 
library(mvtnorm) 
# Generate data 
set.seed(1) 
n <- 100 
p <- 7 
A <- matrix(runif(p^2)*2-1, ncol=p) 
Sigma <- cov2cor(t(A) %*% A) 
sample_df <- data.frame(rmvnorm(n, mean=rep(0,p), sigma=Sigma)) 
colnames(sample_df) <- c("KUM", "MHP", "WEB", "OSH", "JAC", "WSW", "gaugings") 

# Matrix of plots 
p1 <- ggpairs(sample_df, lower = list(continuous = "smooth")) 
# Correlation matrix plot 
p2 <- ggcorr(sample_df, label = TRUE, label_round = 2) 

相關矩陣情節是:

enter image description here

# Get list of colors from the correlation matrix plot 
library(ggplot2) 
g2 <- ggplotGrob(p2) 
colors <- g2$grobs[[6]]$children[[3]]$gp$fill 

# Change background color to tiles in the upper triangular matrix of plots 
idx <- 1 
for (k1 in 1:(p-1)) { 
    for (k2 in (k1+1):p) { 
    plt <- getPlot(p1,k1,k2) + 
    theme(panel.background = element_rect(fill = colors[idx], color="white"), 
      panel.grid.major = element_line(color=colors[idx])) 
    p1 <- putPlot(p1,plt,k1,k2) 
    idx <- idx+1 
} 
} 
print(p1) 

enter image description here