简体   繁体   中英

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.

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

条形图

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM