如何在R中创建一个相关热图(有例子)

439 阅读2分钟

你可以使用下面的基本语法在R中创建一个相关的热图:

#calculate correlation between each pairwise combination of variables
cor_df <- round(cor(df), 2)

#melt the data frame
melted_cormat <- melt(cor_df)

#create correlation heatmap
ggplot(data = melted_cormat, aes(x=Var1, y=Var2, fill=value)) + 
  geom_tile() +
  geom_text(aes(Var2, Var1, label = value), size = 5) +
  scale_fill_gradient2(low = "blue", high = "red",
                       limit = c(-1,1), name="Correlation") +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        panel.background = element_blank())

下面的例子显示了如何在实践中使用这种语法。

例子:在R中创建相关热图

假设我们在R中拥有以下数据框,显示了八个不同的篮球运动员的各种统计数据:

#create data frame
df <- data.frame(points=c(22, 25, 30, 16, 14, 18, 29, 22),
                 assists=c(4, 4, 5, 7, 8, 6, 7, 12),
                 rebounds=c(10, 7, 7, 6, 8, 5, 4, 3),
                 blocks=c(12, 4, 4, 6, 5, 3, 8, 5))

#view data frame
df

  points assists rebounds blocks
1     22       4       10     12
2     25       4        7      4
3     30       5        7      4
4     16       7        6      6
5     14       8        8      5
6     18       6        5      3
7     29       7        4      8
8     22      12        3      5

假设我们想创建一个相关热图,以可视化数据框中每一对变量组合之间的相关系数

在创建相关热图之前,我们必须首先使用cor()计算每个变量之间的相关系数,然后使用reshape2包中的melt()函数将结果转换成可用的格式:

library(reshape2)

#calculate correlation coefficients, rounded to 2 decimal places
cor_df <- round(cor(df), 2)

#melt the data frame
melted_cor <- melt(cor_df)

#view head of melted data frame
head(melted_cor)

      Var1    Var2 value
1   points  points  1.00
2  assists  points -0.27
3 rebounds  points -0.16
4   blocks  points  0.10
5   points assists -0.27
6  assists assists  1.00

接下来,我们可以使用来自ggplot2包的geom_tile()函数来创建相关热图:

library(ggplot2)

#create correlation heatmap
ggplot(data = melted_cor, aes(x=Var1, y=Var2, fill=value)) + 
  geom_tile() +
  geom_text(aes(Var2, Var1, label = value), size = 5) +
  scale_fill_gradient2(low = "blue", high = "red",
                       limit = c(-1,1), name="Correlation") +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        panel.background = element_blank())

correlation heatmap in R

其结果是一个相关热图,使我们能够直观地看到每个成对的变量组合之间的相关系数。

在这个特定的热图中,相关系数呈现出以下颜色:

  • 如果它们接近于1,则为蓝色
  • 如果它们接近于0,则为白色
  • 如果它们接近于1,则为红色

scale_fill_gradient2()函数中,对于参数和参数,你可以随意使用任何你想要的颜色。

例如,你可以用 "红色 "作为低值,用 "绿色 "作为高值:

library(ggplot2)

#create correlation heatmap
ggplot(data = melted_cor, aes(x=Var1, y=Var2, fill=value)) + 
  geom_tile() +
  geom_text(aes(Var2, Var1, label = value), size = 5) +
  scale_fill_gradient2(low = "red", high = "green",
                       limit = c(-1,1), name="Correlation") +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        panel.background = element_blank())

correlation heatmap in R with custom colors

注意:如果你想对相关热图中的确切颜色有更多的控制,你也可以指定使用十六进制颜色代码。