如何在 Alluvial/Sankey 图(在 R ggalluvial 上)的流量项上添加值标签?

INe*_*des 3 r data-visualization ggplot2 dataflow-diagram sankey-diagram

我希望在 R 上标记冲积/桑基图的“流量”部分。

层(列)可以很容易地被标记,但连接它们的流却不能。我所有阅读文档和实验的尝试都没有成功。

在下面的示例中,“freq”预计会标记在流量连接部分上。

图表

library(ggplot2)
library(ggalluvial)

data(vaccinations)
levels(vaccinations$response) <- rev(levels(vaccinations$response))
ggplot(vaccinations,
       aes(x = survey, stratum = response, alluvium = subject,
           y = freq,
           fill = response, label = freq)) +
  scale_x_discrete(expand = c(.1, .1)) +
  geom_flow() +
  geom_stratum(alpha = .5) +
  geom_text(stat = "stratum", size = 3) +
  theme(legend.position = "bottom") +
  ggtitle("vaccination survey responses at three points in time")
Run Code Online (Sandbox Code Playgroud)

teu*_*and 5

有一个选项可以获取原始数字并将其用作流程部分的标签:

ggplot(vaccinations,
       aes(x = survey, stratum = response, alluvium = subject,
           y = freq,
           fill = response, label = freq)) +
  scale_x_discrete(expand = c(.1, .1)) +
  geom_flow() +
  geom_stratum(alpha = .5) +
  geom_text(stat = "stratum", size = 3) +
  geom_text(stat = "flow", nudge_x = 0.2) +
  theme(legend.position = "bottom") +
  ggtitle("vaccination survey responses at three points in time")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果您想更好地控制如何标记这些点,您可以提取图层数据并对其进行计算。例如,我们可以仅计算起始位置的分数,如下所示:

# Assume 'g' is the previous plot object saved under a variable
newdat <- layer_data(g)
newdat <- newdat[newdat$side == "start", ]
split <- split(newdat, interaction(newdat$stratum, newdat$x))
split <- lapply(split, function(dat) {
  dat$label <- dat$label / sum(dat$label)
  dat
})
newdat <- do.call(rbind, split)

ggplot(vaccinations,
       aes(x = survey, stratum = response, alluvium = subject,
           y = freq,
           fill = response, label = freq)) +
  scale_x_discrete(expand = c(.1, .1)) +
  geom_flow() +
  geom_stratum(alpha = .5) +
  geom_text(stat = "stratum", size = 3) +
  geom_text(data = newdat, aes(x = xmin + 0.4, y = y, label = format(label, digits = 1)),
            inherit.aes = FALSE) +
  theme(legend.position = "bottom") +
  ggtitle("vaccination survey responses at three points in time")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这仍然是关于您想要将标签放置在何处的判断。一开始就这样做是简单的方法,但如果您希望这些标签大约位于中间并相互躲避,则需要进行一些处理。