r - 带值的热图(ggplot2)

标签 r ggplot2

我见过在各种 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/

相关文章:

r - 可移植地使用 dyn.load 来调用 R 包中的 C 函数

r - 为数据框的每一行生成一个图

r - ggplot2 : How to change axis/tick thickness中的图形参数

r - ggforce facet_zoom 如何仅注释缩放的图形

python - 无法在 python jupyter 笔记本中使用 ggplot2

javascript - 如何使用 R 从国家文件馆 (archives.gov) 中抓取目录系列中的所有文件

根据另一个数据框中的列删除行

r - 如何向 ggplot2 堆积条形图添加构面?

r - 两个数据系列叠加在同一个条形图/直方图上

r - ggplots 存储在绘图列表中,以在 for 循环内生成绘图时尊重变量值