Omry Atia
Omry Atia

Reputation: 2443

ggplot add aggregated summaries to a bar plot

I have the following data frame:

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)

I would like to create a stacked bar plot, and add a summary of each StepsGroup on top of each bar. So the first group will have 2225, the second 5344 and the third 699.

I am using the following script:

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

The part until before the geom_text works, but for the last bit I get the following error:

Error: This function should not be called directly

Any idea how to add the aggregated quantity?

Upvotes: 1

Views: 216

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389135

We could create a new dataframe stacked_df which would have sum for each 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

Upvotes: 2

Related Questions