在R中如何将dataframe转换为可视化矩阵图展示子流域水质参数
你需要先将长格式的原始数据转换为「行对应子流域、列对应水质参数」的宽结构,再做矩阵可视化即可,以下是可直接运行的实现代码:
首先加载依赖包:
# 用tidyverse生态即可匹配你日常的处理习惯 library(tidyverse)
修正并读取你提供的示例数据:
df <- read.table(text = "parameter basin land ph 1 3.02 COD 1 1.37 OD 1 1.25 N 1 1.85 ph 2 1.71 COD 2 2.02 OD 2 2.96 N 2 1.59 ph 3 2.42 COD 3 2.81 OD 3 1.56 N 3 1.43 ", sep = "", header = TRUE)
方案1:用ggplot2实现自定义程度高的矩阵热图
df %>% ggplot(aes( x = parameter, y = factor(basin, levels = rev(unique(basin))), # 反转y轴让子流域编号从上到下递增 fill = land )) + geom_tile(color = "white", size = 0.5) + # 加白色单元格边框更清晰 geom_text(aes(label = round(land, 2)), color = "white", size = 3) + # 可选:显示单元格内数值 scale_fill_viridis_c() + # 渐变配色可自行替换 labs(x = "水质参数", y = "子流域", fill = "参数值") + theme_bw() + theme( axis.text.x = element_text(angle = 45, hjust = 1), panel.grid = element_blank() )
方案2:用pheatmap快速输出矩阵图
如果不需要太复杂的自定义,用热图包一键生成即可:
library(pheatmap) # 先转成宽格式矩阵 df_wide <- df %>% pivot_wider(names_from = parameter, values_from = land) %>% column_to_rownames("basin") %>% as.matrix() # 绘图,关闭默认的聚类即可得到你要的原始顺序矩阵 pheatmap( df_wide, cluster_rows = FALSE, cluster_cols = FALSE, show_rownames = TRUE, show_colnames = TRUE, xlab = "水质参数", ylab = "子流域", main = "子流域水质参数矩阵" )
两种方案都可以适配你19×10的真实数据,直接替换示例数据即可运行。
内容的提问来源于stack exchange,提问作者wesleysc352
相关产品推荐
相关产品推荐

