2017-08-25 136 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