如何使用 ggplot 和 ggalluvial 正确地用数字标记层?

How can I correctly label stratum with numbers using ggplot and ggalluvial?

我正在尝试创建凹凸图以使用 ggalluvial 可视化时间序列数据。我想使用与该层相关的值“百分比”来标记每个层的中心。我似乎无法获得正确的标签。例如,顶部的值 (12, 14, 8) 应该位于 18-30 矿脉的中心,但由于某种原因它们在 30-40 矿脉的顶部被发现。有没有办法正确标记这个?我也考虑过 geom_sankey_bump.

df <- data.frame(age = c(
  '18-30', '18-30',  '18-30', 
  '30-40', '30-40', '30-40',
  '40-50', '40-50', '40-50',
  '50+', '50+', '50+'),
  year = c(2012, 2013, 2014,
           2012, 2013, 2014,
           2012, 2013, 2014,
           2012, 2013, 2014),
  percent = c(12, 14, 8,
              44, 54, 50,
              21, 32, 45,
              10, 13, 30))

plot <- ggplot(data =df, 
       aes(x = factor(year),
           y = percent,
           alluvium = age,
           node = factor(year),
           stratum = age,
           label = percent) ) 

plot + 
  geom_stratum(aes(stratum = age), decreasing = F, width = 3/4) + 
  geom_alluvium(aes(fill = age), alpha = 1, decreasing = F, 
                     width = 3/4,
                     knot.prop = T,
                     curve_type = "linear") +
  ggfittext::geom_fit_text(stat = "stratum", width = 1/4, min.size = 3) + 
  ggtitle("Marijuana Crime Rate") + 
  theme(plot.title = element_text(hjust = 0.5)) +
  xlab(NULL) + 
  theme_classic() +
  theme(legend.position = "bottom") 

要将标签放置在正确的位置,您必须为 stat_stratum 使用相同的参数,即使用 width=3/4decreasing=FALSE,就像您为 geom_stratum 所做的那样:

library(ggplot2)
library(ggalluvial)

plot <- ggplot(data =df, 
               aes(x = factor(year),
                   y = percent,
                   alluvium = age,
                   node = factor(year),
                   stratum = age,
                   label = percent) ) 

plot + 
  geom_stratum(aes(stratum = age), decreasing = F, width = 3/4) + 
  geom_alluvium(aes(fill = age), alpha = 1, decreasing = F, 
                width = 3/4,
                knot.prop = T,
                curve_type = "linear") +
  ggfittext::geom_fit_text(stat = "stratum", width = 3/4, decreasing = FALSE, min.size = 3) + 
  ggtitle("Marijuana Crime Rate") + 
  theme(plot.title = element_text(hjust = 0.5)) +
  xlab(NULL) + 
  theme_classic() +
  theme(legend.position = "bottom")