如何在R中绘制带纹理的多步骤黑白冲积图?
多步骤黑白纹理冲积图实现方案
数据准备
首先定义原始数据框:
df <- data.frame(Variable = c("X1", "X2", "X3", "X4", "X5", "X6"), Pearson1 = c(6, 3, 2, 5, 4, 1), Spearman1 = c(6, 5, 1, 2, 3, 4), Kendall1 = c(6, 5, 1, 2, 3, 4), Pearson2 = c(6, 5, 1, 2, 3, 4), Spearman2 = c(6, 5, 1, 2, 4, 3), Kendall2 = c(6, 5, 1, 2, 3, 4))
原代码问题分析
你之前的代码无法实现需求,核心问题有三点:
- 错误使用
freq = "value":此处value是排名值,并非冲积图所需的频数统计,应该基于变量的分组关系构建连接 - 未指定步骤顺序,无法将
Variable列为第一个展示步骤 - 未实现黑白风格下用纹理/线型区分变量的需求
可行解决方案
推荐使用ggalluvial(基于ggplot2,自定义性更强)来实现需求,以下是完整步骤:
1. 数据格式转换
将宽格式数据转为适合冲积图的长格式,并明确步骤顺序:
library(tidyverse) library(ggalluvial) df_long <- df %>% # 转换为长格式,拆分类别与排名 pivot_longer(cols = -Variable, names_to = "Category", values_to = "Rank") %>% # 添加步骤序号,确保Variable为第一步 mutate(Step = case_when( Category == "Pearson1" ~ 2, Category == "Spearman1" ~ 3, Category == "Kendall1" ~ 4, Category == "Pearson2" ~ 5, Category == "Spearman2" ~ 6, Category == "Kendall2" ~ 7 )) %>% # 补充Variable作为第一步的行数据 bind_rows(df %>% mutate(Category = "Variable", Rank = Variable, Step = 1)) %>% # 按步骤和变量排序,确保连接关系正确 arrange(Step, Variable)
2. 黑白风格冲积图实现
提供两种黑白区分变量的方案:
方案1:用线型区分变量(基础黑白风格)
ggplot(df_long, aes(x = Step, stratum = Rank, alluvium = Variable)) + # 绘制冲积带,用不同线型区分变量,黑白填充 geom_alluvium(aes(linetype = Variable), fill = "white", colour = "black") + # 绘制分层节点,保持黑白风格 geom_stratum(fill = "white", colour = "black") + # 添加节点标签 geom_text(stat = "stratum", aes(label = Rank)) + # 设置步骤名称 scale_x_continuous(breaks = 1:7, labels = c("Variable", "Pearson1", "Spearman1", "Kendall1", "Pearson2", "Spearman2", "Kendall2")) + # 黑白主题,去掉多余网格 theme_bw() + theme(legend.position = "bottom", panel.grid = element_blank()) + # 为6个变量设置不同线型 scale_linetype_manual(values = c("solid", "dashed", "dotted", "dotdash", "longdash", "twodash")) + labs(x = "步骤", y = "")
方案2:用纹理区分变量(更直观的黑白差异)
如果需要更明显的区分效果,可使用ggpattern包添加纹理:
library(ggpattern) ggplot(df_long, aes(x = Step, stratum = Rank, alluvium = Variable)) + # 带纹理的冲积带,用不同纹理区分变量 geom_alluvium_pattern( aes(pattern = Variable), colour = "black", fill = "white", pattern_fill = "black", pattern_density = 0.1, pattern_spacing = 0.02 ) + geom_stratum(fill = "white", colour = "black") + geom_text(stat = "stratum", aes(label = Rank)) + scale_x_continuous(breaks = 1:7, labels = c("Variable", "Pearson1", "Spearman1", "Kendall1", "Pearson2", "Spearman2", "Kendall2")) + theme_bw() + theme(legend.position = "bottom", panel.grid = element_blank()) + # 为6个变量设置不同纹理 scale_pattern_manual(values = c("stripe", "crosshatch", "dot", "circle", "hex", "wave")) + labs(x = "步骤", y = "")
内容的提问来源于stack exchange,提问作者nickolakis
相关产品推荐
相关产品推荐

