如何将二分图转换为自定义颜色刻度的单元格矩阵(R语言)
将二分图转换为带颜色刻度的矩阵热图(R语言)
需求说明
我用R的bipartite包生成了二分图,但希望转换成论文常用的带颜色单元格的矩阵图——这种形式更适合大数据集的读取与可视化。要求:
- 基于交互值为单元格上色
- 支持自定义颜色刻度范围
附原二分图代码与数据集:
原二分图代码
plotweb(data.mat, method="normal", text.rot = 90, labsize = 1, y.width.low = 0.05, col.high = "#66A61E", col.interaction = "#E6AB02", col.low = "#E7298A", bor.col.interaction = NA, arrow="none", empty=TRUE, plot.axes=FALSE, ybig=1)
数据集
data.mat <- structure(c(7336L, 1640L, 26293L, 111533L, 71255L, 161705L, 104046L, 169975L, 395822L, 153999L, 6780L, 10866L, 131162L, 239110L, 130786L, 88922L, 46725L, 99169L, 109625L, 203947L, 2258L, 550L, 47109L, 1813L, 362753L, 14451L, 17025L, 30251L, 308L, 34412L, 11L, 0L, 56988L, 1360L, 4L, 5L, 107L, 31L, 56L, 868L, 31775L, 31L, 327L, 19L, 180L, 4284L, 77L, 27L, 0L, 854L, 5L, 143L, 4622L, 264L, 7945L, 51L, 14545L, 32L, 8L, 126L, 66L, 0L, 6L, 14130L, 5L, 9L, 165L, 1017L, 5L, 115L, 65L, 5L, 9572L, 77L, 820L, 165L, 521L, 788L, 17L, 538L), dim = c(10L, 8L), dimnames = list(c("Arctium lappa", "Cichorium intybus", "Circium arvense", "Circium vulgare", "Hypericum perforatum", "Leucanthemum vulgare", "Plantago lanceolata", "Trifolium pratense", "Trifolium repens", "Tripleurospermum inodorum"), c("Cladosporium", "Alternaria", "Aureobasidium", "X....1", "Golovinomyces", "Podosphaera", "Ampelomyces", "X....2")))
解决方案
方法1:用ggplot2实现高度自定义的矩阵热图
ggplot2可完全控制颜色刻度、标签与布局,适合论文级可视化:
library(ggplot2) library(tidyr) # 1. 将矩阵转换为长格式数据框 data_df <- as.data.frame(data.mat) %>% tibble::rownames_to_column("Plant") %>% pivot_longer(cols = -Plant, names_to = "Fungus", values_to = "Interaction") # 2. 绘制热图,自定义颜色刻度 ggplot(data_df, aes(x = Fungus, y = Plant, fill = Interaction)) + geom_tile(color = "white") + # 单元格白色边框 # 自定义颜色渐变,手动设置刻度范围 scale_fill_gradient2(low = "#E7298A", mid = "#E6AB02", high = "#66A61E", midpoint = median(data_df$Interaction), limits = c(0, max(data_df$Interaction)), # 自定义刻度上下限 name = "交互值") + theme_minimal() + theme( axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1), # X轴标签旋转90度 axis.title = element_text(size = 12), legend.position = "right" ) + labs(x = "真菌", y = "植物")
方法2:用pheatmap快速生成矩阵热图
pheatmap包专门用于热图绘制,操作更快捷:
library(pheatmap) # 直接绘制,自定义颜色与刻度 pheatmap(data.mat, color = colorRampPalette(c("#E7298A", "#E6AB02", "#66A61E"))(100), breaks = seq(0, max(data.mat), length.out = 101), # 自定义刻度范围 border_color = "white", angle_col = 90, # X轴标签旋转90度 main = "植物-真菌交互矩阵热图", legend_title = "交互值" )
关键说明
- 两种方法均支持自定义颜色刻度范围:ggplot2通过
scale_fill_gradient2的limits参数,pheatmap通过breaks参数设置 - 颜色沿用原代码配色:
#E7298A(低交互值)、#E6AB02(中间值)、#66A61E(高交互值) - 矩阵热图比二分图更适合展示大数据集的数值分布,便于快速定位高/低交互值的组合
内容的提问来源于stack exchange,提问作者Katherine Chau
相关产品推荐
相关产品推荐

