My Personal Blog

Home

Making a nice stacked barchart in ggplot

Jan. 24, 2024 | Categories: TIL

The following R code demonstrates how to make a nice stacked barchart using forcats and ggplot.



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")

Leave a comment:

Comments:

On Jan. 24, 2024 Adrien wrote:

Add a picture