如何基于0-1数值数组绘制灰度水平堆叠图及分类变量B配色实现
实现方案
完整可运行代码
# 加载依赖包 library(tidyverse) library(ggpubr) # 构造示例数据,可替换为你实际的5万长度数组 df_wide <- tibble( ID = 1:10, Arr1 = c(0.1,0.1,0.1,0.2,0.2,0.2,0.7,0.7,0.4,0.7), Arr2 = c(0.6,0.6,0.6,0.1,0.1,0.1,0.1,0.1,0.5,0.1), Arr3 = c(0.3,0.3,0.3,0.7,0.7,0.7,0.2,0.2,0.1,0.2), Arr4 = c(0.4,0.6,0.7,0.2,0.1,0.3,0.4,0.5,0.3,0.9), B = c("a","a","a","b","b","b","a","a","a","b") ) # 数值数组长表转换 df_num <- df_wide %>% select(ID, Arr1:Arr4) %>% pivot_longer(cols = -ID, names_to = "array", values_to = "value") # 分类数组B长表转换 df_b <- df_wide %>% select(ID, B) # 定义数值数组通用绘图函数 plot_num_array <- function(arr_name, color_low, color_high){ df_num %>% filter(array == arr_name) %>% ggplot(aes(x = ID, y = 1)) + geom_tile(aes(fill = value), width = 1, height = 1) + scale_fill_gradient(low = color_low, high = color_high, limits = c(0,1)) + scale_y_continuous(breaks = NULL, name = arr_name) + theme_minimal() + theme( axis.title.x = element_blank(), axis.text.x = element_blank(), panel.grid = element_blank(), legend.position = "none" ) } # 生成4个数值数组的绘图对象 # 如需灰度配色,可将color_low设为"white",color_high设为"black" p1 <- plot_num_array("Arr1", "#fff9cc", "#cc9900") # 浅黄到深黄 p2 <- plot_num_array("Arr2", "#e6f7ff", "#0050b3") # 浅蓝到深蓝 p3 <- plot_num_array("Arr3", "#f6ffed", "#389e0d") # 浅绿到深绿 p4 <- plot_num_array("Arr4", "#fff0f6", "#c41d7f") # 浅粉到深紫 # 生成分类数组B的绘图对象 p_b <- df_b %>% ggplot(aes(x = ID, y = 1)) + geom_tile(aes(fill = B), width = 1, height = 1) + scale_fill_manual(values = c("a" = "green", "b" = "pink")) + scale_y_continuous(breaks = NULL, name = "B") + theme_minimal() + theme( axis.title.x = element_blank(), panel.grid = element_blank(), legend.position = "bottom" ) # 合并所有子图,垂直对齐x轴 ggarrange(p1, p2, p3, p4, p_b, ncol = 1, align = "v", heights = rep(1,5))
问题修复说明
- 选择
geom_tile替代geom_col更适配按位置映射颜色的需求,对5万长度的大数据量兼容性更好,不会出现x轴刻度比例异常的问题 - 之前B数组绘图异常的核心原因是错误映射了
color参数(仅控制边框颜色),改为映射fill参数即可实现整块填充 - 所有子图统一了x轴范围,合并时垂直对齐不会出现位置错位,可根据需求自行调整各个子图的配色、图例位置等参数
内容的提问来源于stack exchange,提问作者Rahil Vora
相关产品推荐
相关产品推荐

