Aditya Devarajan
Aditya Devarajan

Reputation: 3

Labels in geom_bar having only x variable and fill factor

I have created a DF based on the following code.

sex <- c("m","f","m","m","m","m","m","f","f","f")
age <- c(">10",">20",">30",">10",">20",">30",">10",">20",">30",">10") 
df1 <- data.frame(sex,age)
ggplot (df1, aes(sex, fill = factor(age))) + geom_bar()

enter image description here

I want to individually label the counts of combination of age and sex

sex="f" and age = ">10" = 1, sex="f" and age = ">20" = 2, sex="f" and age = ">30" = 1, sex="m" and age = ">10" = 3, sex="m" and age = ">20" = 1, sex="m" and age = ">30" = 2

Upvotes: 0

Views: 1170

Answers (2)

mpalanco
mpalanco

Reputation: 13570

I think you want something like this:

ggplot(df1, aes(sex, fill = factor(age))) + geom_bar() + 
  geom_text(stat = "count", aes(y = ..count.., label = ..count..), position = "stack", vjust = 3)

enter image description here

Upvotes: 3

Shirin Elsinghorst
Shirin Elsinghorst

Reputation: 310

Not sure if I understood your question correctly, but do you mean something like this:

df2 <- as.data.frame(table(df1))
df2$sex_age <- paste(df2$sex, df2$age, sep = "_")

ggplot(df2, aes(x = sex_age, y = Freq)) + geom_bar(stat = "identity")

Upvotes: 0

Related Questions