The following R code demonstrates how to make a nice stacked barchart using forcats
and ggplot
.
fct_lump()
lumps the least common values in an 'Other' category.fct_infreq()
reorders the factor level by the number of observations descending.fct_rev()
flips that order, which makes the the factors with the largest observations appear on the bottom of the plot.library(tidyverse)
library(viridis)
library(nycflights13)
flights %>%
mutate(date = ymd(paste(year, month, day, sep = "-")),
citypair = fct_rev(fct_infreq(fct_lump(paste0(origin, "_", dest), n=20)))) %>%
group_by(date, citypair) %>%
summarize(cnt = n()) %>%
ggplot(aes(x = date, y = cnt, fill = citypair)) +
scale_fill_viridis(discrete = T) +
geom_bar(position = "fill", stat = "identity")
On Jan. 24, 2024 Adrien wrote:
Add a picture