0

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
 ...
user3118602
  • 553
  • 5
  • 19

1 Answers1

1

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

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thanks, this does the trick. Will mark this as the correct answer. Do you have a link that explain more on the ggplot syntax you used? It appears that there are many syntax for ggplots which is kind of confusing. – user3118602 Jan 17 '21 at 03:42
  • 1
    Yes, there are various way in which you can do the same thing however, I usually prefer to "prepare" data before plotting. By that I mean values to be on X-axis, Y-axis, labels, fill etc should be present in the dataframe before I go to ggplot code. It is less confusing for me that way. I never use `..count..`, `..prop..` verbs in plotting but that is just me. – Ronak Shah Jan 17 '21 at 03:50