0
votes

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.

2

2 Answers

2
votes

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

1
votes

Try this. Probably the trick is to use position_stack in geom_text.

library(tidyverse)

test <- expand.grid('cat' = LETTERS[1:5], 'cond'= c(F,T), 'year' = 2001:2005)
test$value <- floor((rnorm(nrow(test)))*100)
test$value[test$value < 0] <- 0

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

Created on 2020-06-05 by the reprex package (v0.3.0)