How can I add both count and percentage, something like "11 (2%)", above each bar in a grouped barplot? I can only do it for percentage using the code below. Thanks!
library(dplyr)
library(scales)
library(ggplot2)
print(mtcars %>%
count(cyl = factor(cyl), gear = factor(gear)) %>%
mutate(pct = prop.table(n)) %>%
ggplot(aes(x = cyl, y = pct, fill = gear, label = scales::percent(pct)))
geom_col(position = "dodge")
geom_text(position = position_dodge(width = .9), vjust = -0.5, size = 3)
scale_y_continuous(labels = scales::percent)
theme(axis.title.y = element_blank(),
axis.text.y = element_blank()))
CodePudding user response:
You can do:
library(dplyr)
library(scales)
library(ggplot2)
mtcars %>%
count(cyl = factor(cyl), gear = factor(gear)) %>%
mutate(pct = prop.table(n)) %>%
ggplot(aes(x = cyl, y = pct, fill = gear,
label = paste0(n, "\n(", scales::percent(pct), ")")))
geom_col(position = "dodge")
geom_text(position = position_dodge(width = .9), vjust = -0.5, size = 3)
scale_y_continuous(labels = scales::percent, limits = c(0, 0.5))
theme(axis.title.y = element_blank(),
axis.text.y = element_blank())