如何转换数据以绘制基于stock、newspaper与status的Alluvial plot
转换数据绘制桑基图(Alluvial Plot)的方法
要绘制以stock和newspaper为横轴、连接部分代表status频率的桑基图,核心是先对原始数据做分组频数聚合,再用可视化工具生成图形。以下是具体步骤(基于R语言实现):
1. 准备环境与原始数据
先加载所需的R包,然后定义原始数据框:
# 加载必要包 library(tidyverse) library(ggalluvial) # 原始数据 df <- data.frame( status = c("open", "close", "close", "open/close","close"), stock = c("google", "amazon", "amazon", "yahoo", "amazon"), newspaper = c("times", "newyork", "london", "times", "times") )
2. 关键数据转换:分组统计频数
桑基图需要明确每个stock-newspaper-status组合的出现次数,用count()函数完成聚合:
# 按三个变量分组,统计每组的频数,命名为frequency df_counted <- df %>% count(stock, newspaper, status, name = "frequency")
转换后的数据结构如下:
| stock | newspaper | status | frequency |
|---|---|---|---|
| amazon | london | close | 1 |
| amazon | newyork | close | 1 |
| amazon | times | close | 1 |
| times | open | 1 | |
| yahoo | times | open/close | 1 |
3. 绘制桑基图
用ggalluvial包的函数绘制图形,将聚合后的频数作为连接宽度的依据:
ggplot(df_counted, aes(y = frequency, axis1 = stock, axis2 = newspaper)) + # 绘制连接条,按status区分颜色 geom_alluvium(aes(fill = status), width = 1/12) + # 绘制轴上的区块 geom_stratum(width = 1/12, fill = "white", color = "black") + # 给区块添加标签 geom_text(stat = "stratum", aes(label = after_stat(stratum))) + # 设置横轴名称与间距 scale_x_discrete(limits = c("stock", "newspaper"), expand = c(0.05, 0.05)) + # 设置填充色配色方案 scale_fill_brewer(type = "qual", palette = "Set1") + # 添加标题与标签 labs(title = "Stock-Newspaper Status 桑基图", x = NULL, y = "出现频率", fill = "状态") + theme_minimal()
转换逻辑说明
原始数据是单条事件记录,桑基图需要的是分组汇总后的频数信息——只有明确每个组合的出现次数,才能让连接条的宽度准确反映status的分布频率,避免重复绘制相同的连接。
内容的提问来源于stack exchange,提问作者Erik Brole
相关产品推荐
相关产品推荐

