Skip to content

Instantly share code, notes, and snippets.

@z3tt
Last active Jul 15, 2021
Embed
What would you like to do?
Create colorful bar charts with percentage labels inside each bar
library(tidyverse)
library(systemfonts)
mpg_sum <- mpg %>%
## just use 2008 data
dplyr::filter(year == 2008) %>%
## turn into lumped factors with capitalized names
dplyr::mutate(
manufacturer = stringr::str_to_title(manufacturer),
manufacturer = forcats::fct_lump(manufacturer, n = 10)
) %>%
## add counts
dplyr::count(manufacturer, sort = TRUE) %>%
dplyr::mutate(
## order factor levels by number, put "Other" to end
manufacturer = forcats::fct_rev(forcats::fct_inorder(manufacturer)),
manufacturer = forcats::fct_relevel(manufacturer, "Other", after = 0),
## create percentage labels with .0s
perc = paste0(sprintf("%4.1f", n / sum(n) * 100), "%"),
## customize label for the first category
perc = if_else(row_number() == 1, paste(perc, "of all car models"), perc),
## add custom colors for top 3 and "Other"
color = case_when(
row_number() == 1 ~ "goldenrod1",
row_number() == 2 ~ "mediumpurple1",
row_number() == 3 ~ "coral2",
manufacturer == "Other" ~ "gray80",
## all others should be gray
TRUE ~ "gray55"
)
)
ggplot(mpg_sum, aes(n, manufacturer, fill = manufacturer)) +
geom_col() +
## add text (another option would be stat_summary())
geom_text(
aes(label = paste0(perc, "%")),
## adjust posiiton inside
hjust = 1, nudge_x = -.5,
## label formatting
size = 4, fontface = "bold", family = "Fira Sans"
) +
## reduce spacing between labels and bars
scale_x_continuous(expand = c(.01, .01)) +
## add custom colors
scale_fill_identity(guide = "none") +
## get rid of all elements except y axis labels
theme_void() +
theme(axis.text.y = element_text(size = 14, hjust = 1, family = "Fira Sans"),
plot.margin = margin(rep(15, 4)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment