基于R ggplot2实现矩阵上下三角分示accuracy与speed的热力图
合并上三角(Speed)与下三角(Accuracy)的对角线热力图实现
核心思路
通过数据筛选拆分上下三角区域,分别映射speed和accuracy变量,再添加单元格对角线实现视觉分隔,同时保证两个指标的热力色标适配各自数值范围。
1. 依赖包加载
library(ggplot2) # 若需额外数据格式转换可加载reshape2,本例直接用原宽表即可 # library(reshape2)
2. 数据预处理
假设你的数据集名为df,包含col1、col2、accuracy、speed字段。先给每行标记所属区域,并提取对应展示数值:
# 标记区域:上三角/下三角/对角线 df$region <- ifelse(df$col1 < df$col2, "upper", ifelse(df$col1 > df$col2, "lower", "diag")) # 提取对应区域的展示值:上三角用speed,下三角用accuracy,对角线设为空 df$value <- ifelse(df$region == "upper", df$speed, ifelse(df$region == "lower", df$accuracy, NA_real_))
若已安装
dplyr,用case_when替代嵌套ifelse会更清晰:library(dplyr) df <- df %>% mutate(region = case_when( col1 < col2 ~ "upper", col1 > col2 ~ "lower", TRUE ~ "diag" ), value = case_when( region == "upper" ~ speed, region == "lower" ~ accuracy, TRUE ~ NA_real_ ))
3. 最终绘图代码
# 初始化绘图对象,分图层绘制上下三角+对角线 p <- ggplot() + # 下三角:accuracy热力图 geom_tile(data = df[df$region == "lower", ], aes(x = col2, y = col1, fill = accuracy), color = "white") + # 上三角:speed热力图 geom_tile(data = df[df$region == "upper", ], aes(x = col2, y = col1, fill = speed), color = "white") + # 绘制每个单元格的左下→右上对角线(视觉分隔) geom_segment(data = df, aes(x = as.numeric(col2) - 0.5, y = as.numeric(col1) - 0.5, xend = as.numeric(col2) + 0.5, yend = as.numeric(col1) + 0.5), color = "black", size = 0.5) + # 对角线区域设为空白(可自定义填充色) geom_tile(data = df[df$region == "diag", ], aes(x = col2, y = col1), fill = "white", color = "white") + # 自定义双指标色标:区分accuracy(蓝系)和speed(红系) scale_fill_gradientn(colors = c("#2A9D8F", "#FFFFFF", "#E76F51"), values = c(0, 0.5, 1), breaks = c(min(df$accuracy, na.rm = T), max(df$accuracy, na.rm = T), min(df$speed, na.rm = T), max(df$speed, na.rm = T)), labels = c(paste("Accuracy:", round(min(df$accuracy, na.rm = T), 2)), paste("Accuracy:", round(max(df$accuracy, na.rm = T), 2)), paste("Speed:", round(min(df$speed, na.rm = T), 0)), paste("Speed:", round(max(df$speed, na.rm = T), 0)))) + # 反转y轴,让下三角显示在左下角(符合常规矩阵阅读习惯) scale_y_discrete(limits = rev(levels(df$col1))) + # 标题与标签设置 labs(title = "Accuracy (Lower) & Speed (Upper) Heatmap", x = "Column 2", y = "Column 1", fill = "Metric Value") + # 主题优化 theme_minimal() + theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 45, hjust = 1)) # 输出图像 print(p)
关键细节说明
- 分图层绘制上下三角:避免
speed和accuracy数值范围差异导致的色标失真 - 对角线绘制:通过将离散的
col1/col2转为数值,偏移0.5定位到热力块的边界,实现精准对角线 - 色标自定义:可根据需求调整颜色方案,若需完全独立的双图例,可使用
ggnewscale包实现
内容的提问来源于stack exchange,提问作者Dovini Jayasinghe
相关产品推荐
相关产品推荐

