Search code examples
rggplot2plotbar-chartstacked-chart

How to show value label in stacked and grouped bar chart using ggplot


My question is about how to show data (or value) labels in a stacked and grouped bar chart using ggplot. The chart is in the form of what has been resolved here stacked bars within grouped bar chart .

The code for producing the chart can be found in the first answer of the question in the above link. An example data set is also given in the question in the link. To show the value labels, I tried to extend that code with

+ geom_text(aes(label=value), position=position_dodge(width=0.9), vjust=-0.25)

but this does not work for me. I greatly appreciate any help on this.


Solution

  • You need to move data and aesthetics from geom_bar() up to ggplot() so that geom_text() can use it.

    ggplot(data=test, aes(y = value, x = cat, fill = cond)) +
        geom_bar(stat = "identity", position = "stack") +
        theme_bw() + 
        facet_grid( ~ year) +
        geom_text(aes(label = value), position = "stack")
    

    Then you can play around with labels, e.g. omitting the zeros:

    ggplot(data=test, aes(y = value, x = cat, fill = cond)) +
        geom_bar(stat = "identity", position = "stack") +
        theme_bw() + 
        facet_grid( ~ year) +
        geom_text(aes(label = ifelse(value != 0, value, "")), position = "stack")
    

    ... and adjusting the position by vjust:

    ggplot(data=test, aes(y = value, x = cat, fill = cond)) +
        geom_bar(stat = "identity", position = "stack") +
        theme_bw() + 
        facet_grid( ~ year) +
        geom_text(aes(label = ifelse(value != 0, value, "")), position = "stack", vjust = -0.3)
    

    barplot