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

类似于

当前代码:
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)))发布于 2022-03-22 16:04:45
您可以添加一个普通的旧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))

或者,如果你想让它看起来像标签在上面的情节,你可以这样做:
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))

https://stackoverflow.com/questions/71575126
复制相似问题