【发布时间】:2018-05-08 14:58:03
【问题描述】:
我想使用ggplot2 来制作像this one 这样的上三角相关矩阵。我可以很好地复制那个,但由于某种原因,我真的很想将reshape2 函数转换为tidyr 函数。我认为我可以使用gather 代替melt,但这不起作用。
使用reshape2 的原始结果
library(reshape2)
library(ggplot2)
mydata <- mtcars[, c(1,3,4,5,6,7)]
cormat <- round(cor(mydata),2)
library(reshape2)
melted_cormat <- melt(cormat)
# Get upper triangle of the correlation matrix
get_upper_tri <- function(cormat){
cormat[lower.tri(cormat)]<- NA
return(cormat)
}
upper_tri <- get_upper_tri(cormat)
melted_cormat <- melt(upper_tri, na.rm = TRUE)
ggplot(data = melted_cormat, aes(Var2, Var1, fill = value)) +
geom_tile()
我尝试使用来自tidyr 的gather。
library(tidyverse)
#first correlatoin matrix
cor_base <- round(cor(mydata), 2)
#now UT
cor_base[lower.tri(cor_base)] <- NA
cor_tri <- as.data.frame(cor_base) %>%
rownames_to_column("Var2") %>%
gather(key = Var1, value = value, -Var2, na.rm = TRUE) %>%
as.data.frame()
ggplot(data = cor_tri, aes(x = Var2, y = Var1, fill = value)) +
geom_tile()
这些值都相同,但顺序发生了一些变化,这使得这看起来不对。检查identical 不会返回TRUE,但两个数据帧的值似乎相同...
> identical(cor_tri, melted_cormat)
[1] FALSE
> dim(cor_tri)
[1] 21 3
> dim(melted_cormat)
[1] 21 3
> sum(cor_tri == melted_cormat)
[1] 63
对此有什么想法,还是我应该继续加载reshape2 以完成我的目标?
谢谢。
【问题讨论】:
标签: r matrix ggplot2 tidyr reshape2