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

R ggplot将汇总摘要添加到条形图,r,ggplot2,geom-bar,geom-text,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("&

我有以下数据框:

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)
直到
geom_text
开始工作之前的部分,但对于最后一位,我得到以下错误:

Error: This function should not be called directly

知道如何添加聚合数量吗?

我们可以创建一个新的数据帧
堆叠的_df
,每个
步骤组都有
总和

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))
stacked_df%group_by(StepsGroup)%%>%summary(nsum=sum(n))
ggplot(df)+
geom_bar(aes(y=freq,x=StepsGroup,fill=GlucoseGroup),stat=“identity”)+
geom_文本(数据=堆叠_df,aes(标签=nsum,步骤组,y=1.1))

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