gpt4 book ai didi

r - 使用 geom_tile 可视化表格?

转载 作者:行者123 更新时间:2023-12-04 10:28:53 25 4
gpt4 key购买 nike

我试图显示对 2 个调查问题的响应的密度和相关性。每个问题的答案都是因素 1-5,我想制作一个响应组合表的热图。

我的表格是这样的:

> table(mydata$v47, mydata$v78)

1 2 3 4 5
1 2 0 0 0 0
2 0 2 2 0 0
3 5 7 8 3 0
4 12 11 14 7 1
5 1 1 2 4 1

我要将什么填充函数传递给 geom_tile 以按频率区分表中的流行对?

这段代码

ggplot(data = mydata, aes(x = v47, y = v78)) + geom_tile()

产生这张图片

ugly table

最佳答案

这是前者 ggflucation() 的修改版本,它将图 block 颜色和大小映射到频率:

mydata <- read.table(header = F, text = "
0 1 2 3 4 5
1 2 0 0 0 0
2 0 2 2 0 0
3 5 7 8 3 0
4 12 11 14 7 1
5 1 1 2 4 1")
library(ggplot2)
library(magrittr)
tab <- as.table(t(as.matrix(mydata[-1, -1])) %>% set_colnames(1:5) %>% set_rownames(1:5))

ggfluc <- function(tab) {
if (is.table(tab))
tab <- as.data.frame(t(tab))
tab <- as.data.frame(tab)
oldnames <- names(tab)
names(tab) <- c("x", "y", "result")
tab <- transform(tab, x = as.factor(x), y = as.factor(y), freq = result)
ceiling = max(tab$freq); floor = 0
tab <- transform(tab, freq = sqrt(pmin(freq, ceiling)/ceiling),
border = ifelse(is.na(freq), "grey90", ifelse(freq > ceiling, "grey30", "grey50")))
tab[is.na(tab$freq), "freq"] <- 1
tab <- subset(tab, freq * ceiling >= floor)
nx <- length(levels(tab$x))
ny <- length(levels(tab$y))
p <- ggplot(tab, aes_string(x = "x", y = "y", height = "freq", width = "freq", fill = "result")) +
geom_tile(colour = "white")
p
}
ggfluc(tab)

enter image description here

关于r - 使用 geom_tile 可视化表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28518902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com