我正在寻找最方便的方法,以将四舍五入的百分比标签添加到冲积层中。以下示例中有50种情况。独立于阶段1或2,每个案例都属于A,B或C组。我想在每个阶段显示相对的组隶属关系。
library(ggplot2)
library(ggalluvial)
df <- data.frame('id' = rep(1:50,2),
'stage' = c(rep(1,50), rep(2,50)),
'group' = sample(c('A','B','C'), 100, replace = TRUE))
ggplot(df,
aes(x = stage, stratum = group, alluvium = id, fill = group)) +
scale_x_discrete(expand = c(.1, .1)) +
geom_flow() +
geom_stratum(alpha = .5)
是否有一种方法可以在不计算初始数据帧中的百分比列的情况下将舍入的百分比标签(包括“%”)添加到层次(条形段)?如果我没有完全弄错,geom_text的工作方式与geom_bar()中的工作方式不同。
[不幸的是,我认为如果不计算初始数据帧中的百分比列,您就无法做到。但这可以轻松完成,并通过标签提供更大的灵活性:
library(ggplot2)
library(ggalluvial)
df <- data.frame('id' = rep(1:50,2),
'stage' = c(rep(1,50), rep(2,50)),
'group' = sample(c('A','B','C'), 100, replace = TRUE))
# the list needs to be reversed, as stratums are displayed reversed in the alluvial by default
stratum_list <- df %>%
group_by(stage, group) %>%
summarize(s = n()) %>%
group_by(stage) %>%
mutate(s = percent(s/sum(s), accuracy=0.1)) %>%
arrange(stage, -as.numeric(group)) %>%
.$s
ggplot(df,
aes(x = stage, stratum = group, alluvium = id, fill = group)) +
scale_x_discrete(expand = c(.1, .1)) +
geom_flow() +
geom_stratum(alpha = .5) +
geom_text(stat = "stratum", label=stratum_list)
UPDATE [13/04/2020]
[建议添加stratum_list
作为Yonghao的版本