2

我正在寻找在 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")
4

1 回答 1

3

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

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")

在此处输入图像描述

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

# 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")

在此处输入图像描述

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

于 2019-09-01T13:04:05.463 回答