ggplot2:中等百分比的标准化堆积图

时间:2015-04-15 12:45:06

标签: r ggplot2 data.table

我正在尝试标准化堆积图并将每个填充的百分比放在每个填充的中间。这是一个简单的问题,但我没有处理y值是什么,因为它是隐式的,所以我不确定如何设置:geom_text(aes(y=??, label=paste0(??,"%")))

至于规范化,我已经看到人们事先崩溃并使dt正常化,但我希望学习ggplot-ish的方法。

我是否只需要将dt转换为time-grpmember百分比的摘要表?这将使我直接处理y值(例如,计算'每次填充的中间')。

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("?", "%")))

Graph

1 个答案:

答案 0 :(得分:1)

修改

从大约ggplot 2.1.0开始,geom_text获得position_fill / position_stack,因此不再需要计算也不需要使用美学来定位标签(请参阅{原文如下{1}}。

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))

enter image description here