Search code examples
rggplot2geom-bargeom-text

How to add count labels to stacked graph on R?


So I'm new to R and already checked countless Stack Overflow threads and youtube videos but cant figure out how to do this simple taks. I have a stacked bar graph and wanted to labels on top of each bar for the various values counted.

Here's the basic code:

ggplot(data=cyclist_data2) +
  geom_bar(mapping = aes(x=member_casual, fill=rideable_type))

And the consequent graph:

enter image description here

I've tried adding a geom_text function that I saw in a video but it didn't work:

ggplot(data=cyclist_data2, mapping=aes(x=member_casual, y=rideable_type)) +
  geom_bar(stat = 'identity') +
  geom_text(aes(label = rideable_type), vjust = -0.2, colour = black, size = 5)

Help would be appreciated!


Solution

  • If this is your data

    df
    # A tibble: 6 × 3
      grp   val     frq
      <chr> <chr> <dbl>
    1 a     aw       10
    2 a     dg        8
    3 a     fg        6
    4 b     aw        7
    5 b     dg       10
    6 b     fg        9
    

    use geom_text to add the labels, position_stack gives you the right positions, and vjust lets you shift the labels up and down.

    ggplot(df, aes(grp, frq, fill=val, label=frq)) + 
      geom_bar(stat="identity") + 
      geom_text(position = position_stack(vjust=0.5))
    

    Note that you can replace geom_bar(stat="identity") with geom_col().

    stacked bar plot

    Data

    df <- structure(list(grp = c("a", "a", "a", "b", "b", "b"), val = c("aw", 
    "dg", "fg", "aw", "dg", "fg"), frq = c(10, 8, 6, 7, 10, 9)), class = c("tbl_df", 
    "tbl", "data.frame"), row.names = c(NA, -6L))