簡體   English   中英

R:使用數據框作為熱圖

[英]R: Use dataframe for heatmap

幾天前我已經發布了一個關於熱圖的問題: R 熱圖:為值分配顏色

答案已經對我的問題有很大幫助(感謝@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”到“col5”列組成,有 100 行,每列中的值從 -1 到 2,替換后分別為“負”到“其他”。 現在我想在熱圖的列中顯示 col1 到 col5 的值,並且數據框中的每一行都是熱圖中的一行。

抱歉,我對 R 真的很陌生,我不知道如何將數據框 DF.heatmap 應用於 ggplot 語句。

感謝大家的幫助!

首先,我會根據需要使用您的先例代碼轉換您的數據框,然后使用您的 ggplot 代碼繪制熱圖:

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 軸標簽在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM