在R ggplot2中通过第三个变量对热图Y轴进行分组展示
实现按clarity分组排序Y轴的热图
首先需要注意,你的原始代码直接使用diamonds数据集时,每个cut-color组合对应多个钻石,geom_tile会出现图层重叠的问题,所以第一步建议先聚合数据,计算每个分组的平均carat值,再绘制热图。下面提供两种可行的实现方式:
方法一:使用ggh4x包实现Y轴分组(推荐)
ggh4x扩展包支持更灵活的分面设置,可以将Y轴按clarity分组展示,同时保持热图的连贯性:
library(ggplot2) library(dplyr) library(ggh4x) # 聚合数据:计算每个cut-color-clarity组合的平均carat diamonds_agg <- diamonds %>% group_by(cut, color, clarity) %>% summarise(mean_carat = mean(carat), .groups = "drop") # 按clarity分组排序color,将color转为有序因子 diamonds_agg <- diamonds_agg %>% arrange(clarity, color) %>% mutate(color = factor(color, levels = unique(color))) # 绘制带Y轴分组的热图 ggplot(diamonds_agg, aes(x = cut, y = color, fill = mean_carat)) + geom_tile(color = "white") + # 添加白色边框区分单元格 # 按clarity分面,左侧显示分组标签,不拆分面板 facet_wrap2(vars(clarity), ncol = 1, strip.position = "left", axes = "y") + scale_fill_viridis_c(name = "平均carat") + theme_bw() + theme( strip.background.y = element_rect(fill = "#f5f5f5"), strip.text.y = element_text(angle = 0, hjust = 0, size = 10), axis.title.y = element_blank() )
方法二:手动添加分组分隔线与标签
如果不想额外安装包,可以通过手动添加分隔线和标签实现分组效果:
library(ggplot2) library(dplyr) # 聚合数据并排序 diamonds_agg <- diamonds %>% group_by(cut, color, clarity) %>% summarise(mean_carat = mean(carat), .groups = "drop") %>% arrange(clarity, color) %>% mutate(color = factor(color, levels = unique(color))) # 计算分组分隔线的位置 group_lines <- diamonds_agg %>% group_by(clarity) %>% summarise(y_pos = min(as.integer(color)) - 0.5) # 绘制热图 ggplot(diamonds_agg, aes(x = cut, y = color, fill = mean_carat)) + geom_tile(color = "white") + # 添加分组分隔线 geom_hline(data = group_lines, aes(yintercept = y_pos), color = "black", size = 1) + # 添加分组标签 geom_text(data = group_lines, aes(x = -Inf, y = y_pos + 0.5, label = clarity), hjust = 0, vjust = 0.5, fontface = "bold", size = 4) + scale_fill_viridis_c(name = "平均carat") + theme_bw() + theme( axis.title.y = element_blank(), axis.text.y = element_text(margin = margin(r = 25)) # 预留空间给分组标签 )
两种方法都能实现按clarity对color分组排序的效果,其中方法一的分面样式更清晰规范,适合正式可视化输出。
内容的提问来源于stack exchange,提问作者dbro970
相关产品推荐
相关产品推荐

