ggplot2 中的热图填充问题

Heatmap in ggplot2 issue with fill

我正在尝试使用 ggplot2 制作热图。我想要绘制的是一个矩阵的形式,它是一个函数的结果。

这是数据:

Image   A   B   C   D   E   F   
 1      3   23  45  23  45  90
 2      4   34  34  34  34  89
 3      34  33  24  89  23  67
 4      3   45  234 90  12  78
 5      78  89  34  23  12  56
 6      56  90  56  67  34  45

函数如下:

vector_a <- names(master)[2:4] 
vector_b <- names(master)[5:6]

heatmap_prep <- function(dataframe, vector_a,vector_b){
    dummy <- as.data.frame(matrix(0, nrow=length(vector_a), ncol=length(vector_b)))
    for (i in 1:length(vector_a)){
                first_value <- dataframe[[ vector_a[i]  ]]
                # print(first_value)
            for(j in 1:length(vector_b)){
                    second_value <- dataframe[[ vector_b[j] ]]
 result <- cor(first_value, second_value, method = "spearman")
                    dummy [i,j] <- result
            }
        }

rownames(dummy) <- vector_a
return(as.matrix(dummy))
heatmap_data_matrix1 <- heatmap_prep(master,vector_a, vector_b)

使用 heatmap_data_matrix1 中的数据,我想使用以下代码创建热图:

library(ggplot2)
if (length(grep("ggplot2", (.packages() ))) == 0){
        library(ggplot2) 
    }

p <- ggplot(data = heatmap_data_matrix1, aes(x = vector_a, y = vector_b)
+ geom_tile(aes(fill = ))

但是,这不起作用。我应该如何重新格式化我的 data/code 才能创建此热图?我应该在 "fill=" 下放什么?

谢谢!

由于许多 R 函数被向量化,并且在大多数情况下,您不需要预先分配或定义向量,因此 for 循环是不必要的。您可以简单地 运行 corr(x,y, method = "spearman") 而无需复杂的循环。

关于您的填充内容问题,您需要将数据重塑为 ggplot2 使用的配置(长格式)。

tidyr 中的 gather 函数执行此操作,将相关性的 rows/columns 放入单独的列中,然后使用 r 值进行填充。

library(tidyverse) # for tidyr, tibble, ggplot2, and magrittr

heatmap_function <- function(df, a, b) {

  cor_data <- cor(df[a], df[b], method = "spearman") %>% 
    as.data.frame(rownames = a) %>% 
    rownames_to_column("x") %>% 
    gather(y, fill, -x)

  ggplot(cor_data, aes(x = x, y = y, fill = fill)) +
    geom_tile()

}

这导致:

heatmap_function(master, c("A","B","C"), c("D","E"))