R:将数据帧用于热图 [英] R: Use dataframe for heatmap
本文介绍了R:将数据帧用于热图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
几天前我已经发布了一个关于热图的问题:R heatmap: assign colors to values
答案已经对我的问题帮助很大(感谢@Pedro Alencar),所以这个代码可以工作:
# Library
library(ggplot2)
library(plyr)
set.seed(10)
# Dummy data
x <- LETTERS[1:20]
y <- paste0("var", seq(1,20))
data <- expand.grid(X=x, Y=y)
data$Z <- runif(400, -1, 2)
print (data)
data$Z <- factor(round(data$Z))
data$Z <- revalue(data$Z, c('-1'='negative'))
data$Z <- revalue(data$Z, c('0' = 'no'))
data$Z <- revalue(data$Z, c('1' = 'yes'))
data$Z <- revalue(data$Z, c('2' = 'other'))
# Heatmap
ggplot(data, aes(X, Y, fill= Z)) +
geom_tile() +
theme (axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank()) +
scale_fill_manual(values = c('#DCDCDC', '#888888', '#17334E', '#3773A4'), name = 'Z')
现在,由于我的数据结构不同,我将再次请求有关此主题的帮助。这是我现在的数据结构:
我现在想将@Pedro Alencar的代码应用于具有以下结构的现有数据帧:
DF.heatmap <- data.frame(
round(runif(100, -1, 2)),
round(runif(100, -1, 2)),
round(runif(100, -1, 2)),
round(runif(100, -1, 2)),
round(runif(100, -1, 2)))
colnames (DF.heatmap) <- c("col1", "col2", "col3", "col4", "col5")
DF.heatmap[DF.heatmap == "-1"] <- "negative"
DF.heatmap[DF.heatmap == "0"] <- "no"
DF.heatmap[DF.heatmap == "1"] <- "yes"
DF.heatmap[DF.heatmap == "2"] <- "other"
此数据框由列";col1";to";col5";组成,每列有100行,每列的值从-1到2,替换后的";负";to";Other";。现在,我想在热图的列中显示col1到col5的值,数据帧中的每一行都是热图中的一行。
很抱歉,我对R非常陌生,而且我不知道如何将DataFrame DF.heatmap应用于gglot语句。
感谢大家的帮助!
推荐答案
首先,我将使用您的先例代码根据您的需要转换您的数据帧,然后使用您的ggmap代码绘制热图:
library(tidyr)
library(plyr)
#Create an ID column to keep the row line number
DF.heatmap$ID = rownames(DF.heatmap)
#Reformat your dataframe with only 3 columns
DF = pivot_longer(DF.heatmap,cols=1:5,names_to="Col",values_to="Value")
colnames(DF)=c("X","Y","Z")
#Your ggplot code
DF$Z <- factor(round(DF$Z))
DF$Z <- revalue(DF$Z, c('-1'='negative'))
DF$Z <- revalue(DF$Z, c('0' = 'no'))
DF$Z <- revalue(DF$Z, c('1' = 'yes'))
DF$Z <- revalue(DF$Z, c('2' = 'other'))
#Reorder the rows in descending order
DF$X=as.numeric(DF$X)
DF$X=reorder(DF$X,desc(DF$X))
ggplot(DF, aes(Y, X, fill= Z)) +
geom_tile(color = "white",
lwd = 0.5,
linetype = 1)+
scale_fill_manual(values = c('red', 'green', 'yellow', 'blue'), name = 'Z')
在可以排列绘图使其可读之后,因为这里有许多Y轴标签
这篇关于R:将数据帧用于热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文