【发布时间】:2019-07-25 07:14:53
【问题描述】:
您好,我想创建显示多个变量的共频的热图 让我们看一些代码:
a <- c(1,1,1,1)
b <-c(1,1,1,0)
c<- c(1,1,0,0)
d <- c(1,0,0,0)
df <- cbind(a,b,c,d)
df
a b c d
[1,] 1 1 1 1
[2,] 1 1 1 0
[3,] 1 1 0 0
[4,] 1 0 0 0
'1' 表示现象的发生 '0' 现象没有出现
a 和 b 同频为 75% a 和 c 同频为 50% ...
最后,我想要一个 4x4 矩阵,在 x 和 y 轴上带有列名,并在瓷砖 % 的共频中 a vs a = 100%,a vs. b = 75% 等等。
我可以请求一些帮助吗?
来自 cmets 的解决方案生成:
library(tidyr)
library(ggplot2)
a <- c(1,1,1,1)
b <-c(1,1,1,0)
c<- c(1,1,0,0)
d <- c(1,0,0,0)
df <- cbind(a,b,c,d)
calc_freq <- function(x, y) {
mean(df[, x] == df[, y] & df[, x] == 1 & df[, y] == 1)
}
mat <- outer(colnames(df), colnames(df), Vectorize(calc_freq))
mat
dimnames(mat) <- list(colnames(df), colnames(df))
mat %>% as_tibble() %>% gather %>% ggplot() + aes(key, value) + geom_tile()
我宁愿将来自mat 的 % 作为填充,将 x 轴和 y 轴作为 dinnames(mat)
【问题讨论】:
标签: r ggplot2 heatmap categorical-data