Home > OS >  Add count to each bar in ggplot bar chart
Add count to each bar in ggplot bar chart

Time:10-20

I have a large dataset, which can be exemplified using the below mwe

df <- data.frame("x" = c(1,1,1,2),"value" = c(4,3,5,1), "groupA" = c("A","B","A","B"), "groupB" = c("X","Y","Y","Y"))
df$value <- ifelse(df$groupB == "Y", -df$value, df$value)

I need to plot this, where one group yields fill, another whether it is above or below the x-axis. This can be done as follows:

ggplot(df,aes(x=x,y=value,fill=groupA)) 
    geom_bar(stat="identity") 

This yields the sum of values in each groupB above and below zero, and color codes the bars nicely:

mwe bar chart

enter image description here

However, I also need the count in each instance printed as labels above each bar. Using enter image description here

As you can see the position of the label is defined by the count. I have tried to set y=value, or y=5 (as an example) but this results in an error message.

How can I solve this?

(edited after zx8754 responded)

CodePudding user response:

I mean, it's not pretty, but it works...

library(dplyr)
library(ggplot2)
df %>% 
  group_by(x) %>% 
  mutate(count = ifelse(row_number() == 1, n(), NA)) %>% 
  ggplot(aes(x = x, y = value,fill = groupA)) 
    geom_col()  
    geom_text(aes(label = count, x = x, y = value))

Returns:

enter image description here

CodePudding user response:

If I understand the problem correctly we can use nudge:

ggplot(df,aes(x=x,y=value,fill=groupA)) 
  geom_bar(stat="identity") 
  geom_text(aes(label=..count..,group=x,y=..count..),
  nudge_y = c(1.4,3.3), stat="count")

enter image description here

  • Related