user3118602
user3118602

Reputation: 583

Adding count value in each bar in ggplot?

The syntax that I am using is this:

ggplot(df, aes(years.employed, ..count..)) + geom_bar(aes(fill = credit.rating), position = "dodge") +
   geom_text(stat = 'count', aes(label = ..count.., vjust = 0))

This produce the following chart: enter image description here

The geom_text shows the total frequency count for each years.employed. However, I want the frequency count to show on each bar (e.g years.employed 1 will have around 99 for red, around 190 for green etc.).

I have read this How to put labels over geom_bar for each bar in R with ggplot2 but do not understand how to make it work for count - I feel that ..count.. is the problem here.

Appreciate for some advise here. Thanks.

Edit:

This is a snippet of the dataset (reduced to minimum variables)

official    rebalance     gender    years.employed    credit.rating
   1            0           0             3                nil
   0            0           0             5                nil
   1            1           1             5                nil
   0            0           1             2                C
   1            1           1             3                B
   0            1           1             2                B
   1            1           1             5                A
 ...

Upvotes: 0

Views: 1277

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388807

You can try :

library(dplyr)
library(ggplot2)

df %>%
  count(years.employed, credit.rating) %>%
  ggplot() + aes(years.employed, n, fill = credit.rating, label = n) + 
  geom_col(position = 'dodge') + 
  geom_text(position = position_dodge(width = 1), vjust = -0.5, hjust = 0.5)

Using mtcars as an example dataset :

Before :

ggplot(mtcars, aes(cyl, ..count..)) + 
  geom_bar(aes(fill = factor(am)), position = "dodge") +
  geom_text(stat = 'count', aes(label = ..count.., vjust = 0))

enter image description here

After :


mtcars %>%
  count(cyl, am) %>%
  ggplot() + aes(cyl, n, fill = factor(am), label = n) + 
  geom_col(position = 'dodge') + 
  geom_text(position = position_dodge(width = 1), vjust = -0.5, hjust = 0.5)

enter image description here

Upvotes: 1

Related Questions