ggplot2:mid-percentage 的归一化堆积图

ggplot2: Normalized stacked plot with mid-percentage

我正在尝试规范化堆叠图并将每个填充的百分比放在每个填充的中间。这是一个简单的问题,但我不知道 y-value 是什么,因为它是隐式的,所以我不确定如何设置:geom_text(aes(y=??, label=paste0(??,"%"))).

至于归一化,我看到有人崩溃并预先归一化 dt,但我希望学习 ggplot-ish 方法来做到这一点。

我是否只需要将 dt 转换为 time-grpmember 百分比的摘要 table?那会让我直接处理 y-values(例如计算 'middle of each fill')。

dt <- as.data.table(read.table(text = "time grpmember
1 TRUE
1 TRUE
1 TRUE
1 FALSE
1 FALSE
1 FALSE
2 FALSE
2 TRUE
2 TRUE
2 TRUE", header=TRUE))
dt$time <- as.factor(dt$time)

ggplot(dt, aes(x=time)) + geom_bar(aes(fill=grpmember)) + geom_text(aes(y = 2, label=paste0("?", "%")))

编辑

从大约 ggplot 2.1.0 开始,geom_text 得到 position_fill / position_stack,因此不再需要计算或使用 y 美学来定位标签(请参阅下方原文中的 pos

dt <- read.table(text = "time grpmember
1 TRUE
1 TRUE
1 TRUE
1 FALSE
1 FALSE
1 FALSE
2 FALSE
2 TRUE
2 TRUE
2 TRUE", header=TRUE)
dt$time <- as.factor(dt$time)

library(ggplot2)
library(dplyr)

dtSummary = dt %>%
   group_by(time, grpmember) %>%
   summarise(count = n()) %>%
   mutate(Percent = paste0(sprintf("%.1f", count / sum(count) * 100), "%")) 

ggplot(dtSummary, aes(x = time, y = count, fill = grpmember, label = Percent)) + 
   geom_bar(position = "stack", stat = "identity") + 
   geom_text(position = position_stack(vjust = .5))



原创

我不太确定你在找什么,但这会计算一个摘要 table,其中包含计数、标签(即百分比)和标签的位置(在每个段的中点);然后画图。

dt <- read.table(text = "time grpmember
1 TRUE
1 TRUE
1 TRUE
1 FALSE
1 FALSE
1 FALSE
2 FALSE
2 TRUE
2 TRUE
2 TRUE", header=TRUE)
dt$time <- as.factor(dt$time)

library(ggplot2)
library(dplyr)

dtSummary = dt %>%
 # Get the counts
   group_by(time, grpmember) %>%
   summarise(count = n()) %>%
# Get labels and position of labels
   group_by(time) %>%
   mutate(Percent = paste0(sprintf("%.1f", count / sum(count) * 100), "%")) %>%
   mutate(pos = cumsum(count) - 0.5 * count)%>%
   mutate(pos = cumsum(count) - 0.5 * count)  %>%
   mutate(grpmember = factor(grpmember),
          grpmember = factor(grpmember, levels = rev(levels(grpmember))))

ggplot(dtSummary, aes(x = time, y = count, fill = grpmember)) + 
   geom_bar(stat = "identity") + 
   geom_text(aes(y = pos, label = Percent))