如何在具有冲积作用的冲积图中向层中添加百分比值?

问题描述 投票:1回答:1

我正在寻找最方便的方法,以将四舍五入的百分比标签添加到冲积层中。以下示例中有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)

enter image description here

是否有一种方法可以在不计算初始数据帧中的百分比列的情况下将舍入的百分比标签(包括“%”)添加到层次(条形段)?如果我没有完全弄错,geom_text的工作方式与geom_bar()中的工作方式不同。

r ggplot2 label
1个回答
0
投票

[不幸的是,我认为如果不计算初始数据帧中的百分比列,您就无法做到。但这可以轻松完成,并通过标签提供更大的灵活性:

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)

enter image description here

UPDATE [13/04/2020]

[建议添加stratum_list作为Yonghao的版本

© www.soinside.com 2019 - 2024. All rights reserved.