Reju V S
Reju V S

Reputation: 17

How to place data labels on stacked bar chart with categorical variables in R?

How do I place data labels on stacked bar charts using the following data set and code. I am getting Error: geom_text requires the following missing aesthetics: y and label when I used + geom_text(aes(X = Educational_status)).

Age Sex Educational_status  State
44  Male    Illiterate       A
35  Male    PG               B
60  Male    UG               C
45  Female  Illiterate       D
45  Female  UG               A
34  Female  Illiterate       A

ggplot(data2, aes(x= Educational_status, fill=Sex))+
  geom_bar(position = "stack")+ 
   + facet_grid( ~ State)

Upvotes: 0

Views: 3616

Answers (2)

Tech Commodities
Tech Commodities

Reputation: 1959

You don't say if there will be multiple people with the same credentials, but if there is only one, then this gives you the labels:

ggplot(data2, aes(x = Educational_status, y = 1, fill = Sex, label = Sex)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5)) +
  facet_grid( ~ State)

Change the vjust to move the label up or down, and label = Sex if you want a different label

enter image description here

Upvotes: 2

stefan
stefan

Reputation: 125797

Maybe this is what you are looking for. To add labels on a bar chart there are at least two approaches. Either approach requires to compute the y values to place the labels and to map something on the label aes.

  1. Using geom_bar you have to tell ggplot2 to compute the count on the fly inside geom_text by setting stat = "count". If you want to use the count for the labels as well, you could make use of after_stat(count).

  2. The probably easier way would be to aggregate the data using e.g. dplyr::count before passing it to ggplot and making use of geom_col.

library(ggplot2)

ggplot(data2, aes(x = Educational_status, fill = Sex)) +
  geom_bar() +
  geom_text(aes(label = after_stat(count)), stat = "count", position = "stack", vjust = 0) +
  facet_grid(. ~ State)

library(dplyr)

data3 <- data2 %>%
  count(Educational_status, Sex, State, name = "count")

ggplot(data3, aes(x = Educational_status, y = count, fill = Sex)) +
  geom_col() +
  geom_text(aes(label = count), position = "stack", vjust = 0) +
  facet_grid(. ~ State)

DATA

data2 <- structure(list(Age = c(44L, 35L, 60L, 45L, 45L, 34L), Sex = c(
  "Male",
  "Male", "Male", "Female", "Female", "Female"
), Educational_status = c(
  "Illiterate",
  "PG", "UG", "Illiterate", "UG", "Illiterate"
), State = c(
  "A",
  "B", "C", "D", "A", "A"
)), class = "data.frame", row.names = c(
  NA,
  -6L
))

Upvotes: 1

Related Questions