ggplot将汇总的摘要添加到条形图

时间:2018-10-15 07:47:19

标签: r ggplot2 geom-bar geom-text

我有以下数据框:

structure(list(StepsGroup = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 
3L, 3L, 3L), .Label = c("(-Inf,3e+03]", "(3e+03,1.2e+04]", "(1.2e+04, Inf]"
), class = "factor"), GlucoseGroup = structure(c(1L, 2L, 3L, 
1L, 2L, 3L, 1L, 2L, 3L), .Label = c("<100", "100-180", ">180"
), class = "factor"), n = c(396L, 1600L, 229L, 787L, 4182L, 375L, 
110L, 534L, 55L), freq = c(0.177977528089888, 0.719101123595506, 
0.102921348314607, 0.147267964071856, 0.782559880239521, 0.0701721556886228, 
0.157367668097282, 0.763948497854077, 0.0786838340486409)), class = 
c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -9L), vars = "StepsGroup", 
labels = structure(list(
StepsGroup = structure(1:3, .Label = c("(-Inf,3e+03]", "(3e+03,1.2e+04]", 
"(1.2e+04, Inf]"), class = "factor")), class = "data.frame", row.names = 
c(NA, -3L), vars = "StepsGroup", drop = TRUE), indices = list(0:2, 
3:5, 6:8), drop = TRUE, group_sizes = c(3L, 3L, 3L), biggest_group_size = 
3L)

我想创建一个堆叠的条形图,并在每个条形的顶部添加每个StepsGroup的摘要。因此,第一组将有2225,第二组5344和第三699。

我正在使用以下脚本:

ggplot(d_stepsFastingSummary , aes(y = freq, x = StepsGroup, fill = 
GlucoseGroup)) + geom_bar(stat = "identity") +
 geom_text(aes(label = sum(n()), vjust = 0))

直到geom_text工作之前的零件,但最后我得到以下错误:

Error: This function should not be called directly

您知道如何添加汇总数量吗?

1 个答案:

答案 0 :(得分:2)

我们可以创建一个新的数据框stacked_df,每个sum都会有StepsGroup

stacked_df <- df %>% group_by(StepsGroup) %>% summarise(nsum = sum(n))


ggplot(df) + 
   geom_bar(aes(y = freq, x = StepsGroup, fill= GlucoseGroup),stat = "identity") +
   geom_text(data = stacked_df, aes(label = nsum, StepsGroup,y = 1.1))

enter image description here