Add labels to stacked barplot

I am unable to add labels to stacked barplot. Given below is a sample of the data.

Month

Type

n

March Cardio 1
March Core 1
March Strength 4
March Yoga 1
April Cardio 2
April Core 3
April Strength 5
May Boxing 1
May Cardio 3
May Strength 5

Please help. I am plotting using ggplot. Below is the code I have used.

daytype20 %>%
ggplot(aes(Month, n, fill = Type)) +
geom_bar(stat = "identity", position = "stack") +
labs(title = "No of Days of each workout Month-wise in 2020") +
geom_text(aes(label = round(n, 3)), position = position_dodge(0.9), vjust = 4, hjust = 4, size = 4) +
geom_col(aes(fill = Type), width = 0.7) +
theme_bw()

Took the liberty of cleaning up the code a bit - Would this work for you?

# Load libraries
library("tidyverse")

# Define data
my_data <- tribble(
  ~Month, ~Type, ~n,
  "March", "Cardio", 1,
  "March", "Core", 1,
  "March", "Strength", 4,
  "March", "Yoga", 1,
  "April", "Cardio", 2,
  "April", "Core", 3,
  "April", "Strength", 5,
  "May", "Boxing", 1,
  "May", "Cardio", 3,
  "May", "Strength", 5
)

# Visualise
my_data %>% 
  ggplot(aes(x = Month,
             y = n,
             fill = Type,
             label = n)) +
  geom_col() +
  geom_text(position = position_stack(vjust = .5)) +
  labs(title = "No of Days of each workout Month-wise in 2020") +
  theme_bw()

Hope it helps! :slightly_smiling_face:

This works perfect! Thanks :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.