在R中实现Sankeyplot与Barplot联动的tidyverse友好可视化需求
使用Tidyverse实现分类流向+堆叠条形图可视化
步骤1:加载依赖包与读取数据
首先加载所需的tidyverse工具包,以及用于拼接图表的cowplot:
library(tidyverse) library(cowplot)
读取CSV格式的数据集:
df <- read_csv("a.dat")
步骤2:预处理数据
分别计算分类-处理方式的频次,以及处理方式-得分的频次:
# 计算每个分类对应到各处理方式的样本数 cat_treat_counts <- df %>% count(Category, Treatment, name = "count") # 计算每个处理方式下各得分的出现次数,并将得分转为因子类型便于堆叠 treat_score_counts <- df %>% count(Treatment, Score, name = "count") %>% mutate(Score = as.factor(Score))
步骤3:绘制分类流向图(冲积图)
使用ggplot2结合ggalluvial绘制从分类到处理方式的流向关系:
flow_plot <- ggplot(cat_treat_counts, aes(y = count, axis1 = Category, axis2 = Treatment)) + # 绘制流向带 geom_alluvium(aes(fill = Category), width = 1/12, alpha = 0.8) + # 绘制分层节点 geom_stratum(width = 1/12, fill = "white", color = "black") + # 添加节点标签 geom_text(stat = "stratum", aes(label = after_stat(stratum)), size = 4) + # 设置坐标轴与颜色 scale_x_discrete(limits = c("分类", "处理方式"), expand = c(0.1, 0.1)) + scale_fill_brewer(type = "qual", palette = "Set1") + # 优化主题 theme_minimal() + theme(legend.position = "top", axis.title = element_blank(), plot.margin = margin(5, 0, 5, 5))
步骤4:绘制处理方式对应的得分堆叠条形图
为每个处理方式绘制堆叠条形图展示各得分的出现频次:
stacked_plot <- ggplot(treat_score_counts, aes(x = Treatment, y = count, fill = Score)) + # 绘制堆叠条形 geom_col(position = "stack", width = 0.7) + # 添加条形内的数量标签 geom_text(aes(label = count), position = position_stack(vjust = 0.5), size = 3.5) + # 设置颜色与坐标轴 scale_fill_viridis_d(option = "plasma") + labs(fill = "得分") + # 优化主题 theme_minimal() + theme(axis.title.x = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank(), plot.margin = margin(5, 5, 5, 0))
步骤5:拼接两个图表
使用cowplot将流向图与堆叠条形图拼接为一个整体:
final_plot <- plot_grid(flow_plot, stacked_plot, rel_widths = c(1, 1), align = "h") # 保存图表(可选) ggsave("category_treatment_score_plot.png", final_plot, width = 12, height = 6, dpi = 300)
效果说明
- 左侧冲积图清晰展示了不同分类(Red/Blue/Green/Yellow)到各处理方式(Compact/Expand/Neutral/Destroy)的样本流向与数量
- 右侧堆叠条形图对应每个处理方式,直观呈现各得分的出现频次,标签标注具体数值
- 配色采用区分度高的调色板,确保不同分类与得分的辨识度
内容的提问来源于stack exchange,提问作者Ginko-Mitten
相关产品推荐
相关产品推荐

