带值的热图(ggplot2) [英] heatmap with values (ggplot2)
问题描述
我已经看到了在各种R图形系统(包括点阵和基点)中生成的值的热点图,如下所示:
$ b
我倾向于使用 ggplot2
一点点,并希望能够绘制出相应的单元格值的热图。这里是热图,尝试使用 geom_text
:
library(reshape2 ,ggplot2)
dat < - matrix(rnorm(100,3,1),ncol = 10)
名称(dat)< - paste(X,1:10)
2 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的评论我很容易做到这一点: $ b
library(tidyverse)
## make data
dat < - matrix(rnorm(100,3,1),ncol = 10)
##整形数据(tidy /高形式)
dat2 < - dat%>>%
tbl_df()%>%
rownames_to_column ('Var1')%>%
collect(Var2,value,-Var1)%>%
mutate(
Var1 = factor(Var1,levels = 1:10),
Var2 = factor(gsub(V,,Var2),levels = 1:10)
)
##绘图数据
ggplot(dat2, aes(Var1,Var2))+
geom_tile(aes(fill = value))+
geom_text(aes(label = round(value,1)))+
scale_fill_gradient(low =白色,高=红色)
p>
I've seen heatmaps with values made in various R graphics systems including lattice and base like this:
I tend to use ggplot2
a bit and would like to be able to make a heatmap with the corresponding cell values plotted. Here's the heat map and an attempt using 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)
Normally I can figure out the x and y values to pass but I don't know in this case since this info isn't stored in the data set. How can I place the text on the heatmap?
This has been updated to conform to tidyverse principles and improve poor use of ggplot2
Per SlowLeraner's comment I was easily able to do this:
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")
这篇关于带值的热图(ggplot2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!