gpt4 book ai didi

r - 带值的热图(ggplot2)

转载 作者:行者123 更新时间:2023-12-03 08:45:08 25 4
gpt4 key购买 nike

我见过在各种 R 图形系统(包括点阵和基础)中生成的热图,如下所示:

enter image description here

我倾向于使用 ggplot2有点,并希望能够制作带有绘制的相应单元格值的热图。这是热图和尝试使用 geom_text :

library(reshape2, ggplot2)
dat <- matrix(rnorm(100, 3, 1), ncol=10)
names(dat) <- paste("X", 1:10)
dat2 <- melt(dat, id.var = "X1")
p1 <- ggplot(dat2, aes(as.factor(Var1), Var2, group=Var2)) +
geom_tile(aes(fill = value)) +
scale_fill_gradient(low = "white", high = "red")
p1

#attempt
labs <- c(apply(round(dat[, -2], 1), 2, as.character))
p1 + geom_text(aes(label=labs), size=1)

通常我可以找出要传递的 x 和 y 值,但在这种情况下我不知道,因为此信息未存储在数据集中。如何将文本放置在热图上?

最佳答案

这已更新以符合 tidyverse 原则并改善 ggplot2 的不良使用

根据 SlowLeraner 的评论,我很容易做到这一点:

library(tidyverse)

## make data
dat <- matrix(rnorm(100, 3, 1), ncol=10)

## reshape data (tidy/tall form)
dat2 <- dat %>%
tbl_df() %>%
rownames_to_column('Var1') %>%
gather(Var2, value, -Var1) %>%
mutate(
Var1 = factor(Var1, levels=1:10),
Var2 = factor(gsub("V", "", Var2), levels=1:10)
)

## plot data
ggplot(dat2, aes(Var1, Var2)) +
geom_tile(aes(fill = value)) +
geom_text(aes(label = round(value, 1))) +
scale_fill_gradient(low = "white", high = "red")

enter image description here

关于r - 带值的热图(ggplot2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14290364/

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