Heatmap Plot with ggplot2 【R】

本文详细介绍如何使用R语言中的ggplot2包绘制热图,包括数据构建、使用geom_tile绘制基本热图、调整格子形状及添加边框等。此外,还介绍了如何通过scale_fill_gradient系列函数改变热图的颜色方案,并提供了调整图例样式的实用代码。

前言

热图,作为生命科学领域常用的数据展示方式,R中已经有很多专门画热图的工具,比如heatmapComplexheatmap等等,但是,有些特殊的需求,还是要用ggplot2实现,最近有这需求,正好整理一下😑

构建数据

library(reshape)
# Data 
set.seed(8)
m <- matrix(round(rnorm(200), 2), 10, 10)
colnames(m) <- paste("Col", 1:10)
rownames(m) <- paste("Row", 1:10)

# Transform the matrix in long format
df <- melt(m)
colnames(df) <- c("x", "y", "value")
head(df)
XYValue
Row 1Col 1-0.08
Row 2Col 10.84
Row 3Col 1-0.46
Row 4Col 1-0.55
Row 5Col 10.74

使用 geom_tile绘制热图

使用geom_tile就可以绘制热图,颜色用value填充

# install.packages("ggplot2")
library(ggplot2)

ggplot(df, aes(x = x, y = y, fill = value)) +
  geom_tile()

在这里插入图片描述

变方

但是,会发现上边的图画出来,每个格子不是方方正正的,所以调整一下,使用:cood_fixed

ggplot(df, aes(x = x, y = y, fill = value)) +
  geom_tile() +
  coord_fixed() 

在这里插入图片描述

给格子加个边框

如果喜欢,可以给每个格子加上特定颜色的边框,比如白色的

ggplot(df, aes(x = x, y = y, fill = value)) +
  geom_tile(color = "white",
            lwd = 1.5,
            linetype = 1) +
  coord_fixed() 

在这里插入图片描述

显示数据

可以像使用其他工具那样,把颜色代表的数值显示出来,使用:geom_text

ggplot(df, aes(x = x, y = y, fill = value)) +
  geom_tile(color = "black") +
  geom_text(aes(label = value), color = "white", size = 4) +
  coord_fixed() 

在这里插入图片描述

颜色

更改颜色,大致有三种途径:scale_fill_gradientscale_fill_gradient2scale_fill_gradientn,下面

使用scale_fill_gradient

通过设置低值和高值对应的颜色来更改热图的颜色:

ggplot(df, aes(x = x, y = y, fill = value)) +
  geom_tile(color = "black") +
  scale_fill_gradient(low = "white", high = "red") +
  coord_fixed() 

在这里插入图片描述

使用scale_fill_gradient2

这个2吧,就是加了一个中值的设置:

ggplot(df, aes(x = x, y = y, fill = value)) +
  geom_tile(color = "black") +
  scale_fill_gradient2(low = "#075AFF",
                       mid = "#FFFFCC",
                       high = "#FF0000") +
  coord_fixed() 

在这里插入图片描述

使用scale_fill_gradientn

这个吧,就得需要自己选颜色了,可以选N多个,下面的例子就是用了调色板的20个颜色:

ggplot(df, aes(x = x, y = y, fill = value)) +
  geom_tile(color = "black") +
  scale_fill_gradientn(colors = hcl.colors(20, "RdYlGn")) +
  coord_fixed() 

在这里插入图片描述

图例

关于图里的修改,其实和画其他的图一样一样的…直接上代码了

长宽

ggplot(df, aes(x = x, y = y, fill = value)) +
  geom_tile(color = "black") +
  coord_fixed() +
  guides(fill = guide_colourbar(barwidth = 0.5,
                                barheight = 20)) 

在这里插入图片描述

Title

ggplot(df, aes(x = x, y = y, fill = value)) +
  geom_tile(color = "black") +
  coord_fixed() +
  guides(fill = guide_colourbar(title = "Title")) 

在这里插入图片描述)

标签

ggplot(df, aes(x = x, y = y, fill = value)) +
  geom_tile(color = "black") +
  coord_fixed() +
  guides(fill = guide_colourbar(label = FALSE,
                                ticks = FALSE)) 

在这里插入图片描述

移除

ggplot(df, aes(x = x, y = y, fill = value)) +
  geom_tile(color = "black") +
  coord_fixed() +
  theme(legend.position = "none") 

就不放图了,就是图例没有了😑

### 使用 `ggplot2` 绘制热图的方法 以下是使用 R 中的 `ggplot2` 包绘制热图的具体方法和示例代码: #### 示例代码 ```r # 加载必要的库 library(ggplot2) # 假设我们有如下矩阵数据 data <- matrix(runif(100, min = 0, max = 1), nrow = 10, ncol = 10) rownames(data) <- paste0("Row_", 1:10) colnames(data) <- paste0("Col_", 1:10) # 将矩阵转换为长格式的数据框 df <- reshape2::melt(data) # 创建热图 heatmap_plot <- ggplot(df, aes(x = Var2, y = Var1, fill = value)) + geom_tile(color = "white") + # 添加矩形边框 scale_fill_gradient(low = "blue", high = "red") + # 设置填充颜色渐变 theme_minimal() + # 应用简约主题 labs(title = "Heatmap Example with ggplot2", # 图表标题 x = "Columns", # X轴标签 y = "Rows", # Y轴标签 fill = "Value") # 颜色图例标签 # 显示热图 print(heatmap_plot) ``` 上述代码展示了如何通过 `reshape2::melt()` 函数将矩阵数据转换成长格式数据框,并利用 `ggplot2` 的 `geom_tile()` 和 `scale_fill_gradient()` 来实现热图可视化[^1]。 --- 如果需要绘制更复杂的热图,比如带有上三角的相关性热图,则可以参考以下代码片段: ```r # 构造相关系数矩阵 cor_matrix <- cor(mtcars[, c("mpg", "cyl", "disp", "hp", "drat")]) # 转换为长格式数据框 corM_long <- reshape2::melt(cor_matrix) # 过滤仅保留上三角部分 upper_triangle <- subset(corM_long, Var1 != Var2 & rowSums(!is.na(corM_long))) # 创建热图 p <- ggplot(upper_triangle, aes(Var1, Var2)) + geom_tile(aes(fill = value), color = "white") + # 矩形单元格 geom_point(aes(size = abs(value), color = value)) + # 散点表示大小关系 scale_color_gradient2(midpoint = 0, low = "blue", mid = "white", high = "red") + # 渐变配色方案 theme_classic() + # 主题样式 coord_fixed(ratio = 1) # 固定纵横比例 # 显示图表 print(p) ``` 此代码实现了带有点状标记的上三角相关性热图,其中单元格的颜色由相关性的强度决定,而散点则进一步强调了绝对值较大的位置[^2]。 --- 对于基础场景下的热图制作,也可以简化流程并专注于核心功能。例如,当处理时间序列中的温度变化时,可以通过以下方式快速构建热图[^3]: ```r # 数据准备 (模拟的时间序列温度数据) set.seed(123) temperature_data <- data.frame( Time = rep(1:7, each = 4), Location = rep(c("A", "B", "C", "D"), times = 7), Temperature = runif(28, min = 15, max = 30) ) # 绘制热图 basic_heatmap <- ggplot(temperature_data, aes(Location, factor(Time))) + geom_tile(aes(fill = Temperature), color = "black") + # 单元格填充颜色 scale_fill_viridis_c(option = "plasma") + # 更现代的色彩映射 labs(title = "Temperature Heatmap by Location and Time", x = "Location", y = "Time Point") # 输出图像 print(basic_heatmap) ``` 这段代码适用于展示地理位置与时间维度上的数值分布情况。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值