Riddle
Riddle

Reputation: 49

Construct a Bar Graph with Overlay with data label Using R

I am trying to add labels in ggplot2 bar graph.


ggplot(bank_train, aes(previous_outcome)) +geom_bar(aes(fill = response))+
  scale_fill_manual(values = c("orange", "lightblue"))

enter image description here

Where bank_train is the name of the dataset that has a variable name as previous_outcome. And, response as of (yes or no).

The code above works fine, but I tried to add numbers inside the bar graph, but it gave me an incorrect graph.

Here is my attempt:


ggplot(bank_train, aes(previous_outcome)) +geom_bar(aes(fill = response),stat = "identity")
+geom_text(aes(label = count),position = position_stack(vjust= 0.5),
            colour = "white", size = 5)+scale_fill_manual(values = c("orange", "lightblue"))

my problem is understanding the geom_text.

Your help is greatly appreciated

Upvotes: 1

Views: 574

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

Use after_stat to get the counts for the geom_text label.

set.seed(2022)
n <- 100L
outcomes <- c("failure", "success", "nonexistent")
previous_outcome <- factor(sample(outcomes, n, TRUE), levels = outcomes)
response <- sample(c("yes", "no"))
bank_train <- data.frame(previous_outcome, response)

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.2.2

ggplot(bank_train, aes(previous_outcome, fill = response)) +
  geom_bar() +
  geom_text(aes(label = after_stat(count)), 
            stat ='count', colour = "white", size = 5,
            position = position_stack(vjust = 0.5)) +
  scale_fill_manual(values = c("orange", "lightblue")) +
  labs(x = 'Previous Outcome', y = 'Count') +
  theme_bw()

Created on 2022-11-12 with reprex v2.0.2


Edit

If the bars are dodged, try position_dodge2, like said in comments, and assign half of after_stat(count) to the y aesthetic.

ggplot(bank_train, aes(previous_outcome, fill = response)) +
  geom_bar(position = "dodge2") +
  geom_text(aes(label = after_stat(count), y = after_stat(count)/2L), 
            stat ='count', colour = "white", size = 5,
            position = position_dodge2(width = 0.9)) +
  scale_fill_manual(values = c("orange", "lightblue")) +
  labs(x = 'Previous Outcome', y = 'Count') +
  theme_bw()

Created on 2022-11-12 with reprex v2.0.2

Upvotes: 2

Related Questions