在轴上方添加标题 geom_alluvium

Add title above axis geom_alluvium

如何在 geom_alluvium 中的 axis1 和 axis2 上方添加标题?

类似于

当前代码:

library(ggplot2)
library(ggalluvial)



df = data.frame(
  before = factor(c(4,2,3,1,1,1,2,4,2,2,1,4,3), labels = c("a","b","c","d")),
  after  = factor(c(3,3,2,1,3,4,4,1,1,2,2,4,3), labels = c("a","b","c","d")),
  N      = c(4,1,1,2,1,2,1,1,1,1,1,1,1)
)

ggplot(df, aes(y = N, axis1 = before, axis2 = after))  + 
  geom_alluvium(aes(fill = before)) +
  geom_stratum() +
  geom_text(stat = "stratum", mapping = aes(label = after_stat(stratum)))

你可以添加一个普通的旧 geom_label:

ggplot(df, aes(y = N, axis1 = before, axis2 = after))  + 
  geom_alluvium(aes(fill = before)) +
  geom_stratum() +
  geom_text(stat = "stratum", mapping = aes(label = after_stat(stratum))) +
  geom_label(inherit.aes = FALSE,
            data = data.frame(x = c(1, 2), y = c(19, 19), 
                              label = c('Before', 'After')),
            aes(label = label, x = x, y = y))

或者,如果你想让标签看起来像 'above' 情节,你可以这样做:

ggplot(df, aes(y = N, axis1 = before, axis2 = after))  + 
  geom_alluvium(aes(fill = before)) +
  geom_stratum() +
  geom_text(stat = "stratum", mapping = aes(label = after_stat(stratum))) +
  annotate('rect', xmin = -Inf, xmax = Inf, ymax = Inf, ymin = 18.5,
           fill = 'white') +
  geom_text(inherit.aes = FALSE,
            data = data.frame(x = c(1, 2), y = c(19, 19), 
                              label = c('Before', 'After')),
            aes(label = label, x = x, y = y))

或者,如果这感觉像作弊,您可以使用 annotate:

ggplot(df, aes(y = N, axis1 = before, axis2 = after))  + 
  geom_alluvium(aes(fill = before)) +
  geom_stratum() +
  geom_text(stat = "stratum", mapping = aes(label = after_stat(stratum))) +
  coord_cartesian(clip = 'off', ylim = c(0, 18)) +
  annotate('text', y = c(20, 20), x = c(1, 2), label = c('Before', 'After')) +
  theme(plot.margin = margin(30, 10, 10, 10))