You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中利用缺失值实现冲积图的流量递减效果?

如何用缺失值实现冲积图的流量递减效果?

我想要制作一张简单的流量图(冲积图),以下是我的R代码:

## Data
x = tibble(qms = c("FLOW", "FLOW"),
           move1 = c("Birth", "Birth"),
           move2 = c("Direct", NA),
           freq = c(100, 50))
## Graph
x %>% 
  mutate(id = qms) %>% 
  to_lodes_form(axis = 2:3, id = id) %>% 
  na.omit() %>% 
  ggplot(aes(x = x, stratum = stratum, alluvium = id,
             y = freq, label = stratum)) +
  scale_x_discrete(expand = c(.1, .1)) +
  geom_flow(aes(fill = qms),stat = "alluvium") +
  geom_stratum(aes(fill = stratum), show.legend=FALSE) +
  geom_text(stat = "stratum", size = 3) 

当前图表结果

图表仅显示FLOW→Birth→Direct的100流量,未呈现Birth之后50流量递减消失的效果。

期望图表效果

FLOW→Birth分为两支:100的流量延续到Direct,50的流量在中途消失,直观体现流量递减模式。


解决方案

问题核心在于两点:

  • 所有流量使用了相同的id,导致分支被合并;
  • na.omit()删除了用来呈现“流量消失”的缺失值行。

修改后的代码如下:

## Data
x = tibble(qms = c("FLOW", "FLOW"),
           move1 = c("Birth", "Birth"),
           move2 = c("Direct", NA),
           freq = c(100, 50),
           id = c("flow_1", "flow_2"))  # 给每条流量分配唯一ID

## Graph
x %>% 
  to_lodes_form(axis = 2:3, id = id) %>%  # 无需删除缺失值
  ggplot(aes(x = x, stratum = stratum, alluvium = id,
             y = freq, label = stratum)) +
  scale_x_discrete(expand = c(.1, .1)) +
  geom_flow(aes(fill = qms), stat = "alluvium") +
  geom_stratum(aes(fill = stratum), show.legend = FALSE) +
  geom_text(stat = "stratum", size = 3)

说明

  1. 唯一ID:给两条流量记录分别分配flow_1和flow_2,让冲积图能识别独立的流量分支,避免合并;
  2. 保留缺失值:移除na.omit()后,缺失的move2对应的行被保留,ggplot会绘制从Birth到NA的流量,但NA对应的分层(stratum)不会显示,刚好呈现出50流量递减消失的效果。

内容的提问来源于stack exchange,提问作者jhyeon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 19:05:23