Skip to content

Instantly share code, notes, and snippets.

@andrewheiss
Created July 28, 2023 19:59
Show Gist options
  • Save andrewheiss/96668ea72ae5a8b08f1224da70c729a3 to your computer and use it in GitHub Desktop.
Save andrewheiss/96668ea72ae5a8b08f1224da70c729a3 to your computer and use it in GitHub Desktop.
library(tidyverse)

# geom_bar() doesn't need a variable mapped to the y-axis; it calculates it on its own behind the scenes
ggplot(mpg, aes(x = drv, fill = factor(year))) +
  geom_bar()

# geom_col() does need a y variable, so you have to make it on your own, like
# within-drive proportions here
mpg_small <- mpg %>% 
  count(drv, year) %>% 
  group_by(drv) %>% 
  mutate(prop = n / sum(n))

# You can put these bars side-by-side with `position = "dodge"`
ggplot(mpg, aes(x = drv, fill = factor(year))) +
  geom_bar(position = "dodge")

# You can change themes with one of the built-in themes, like theme_bw()
ggplot(mpg, aes(x = drv, fill = factor(year))) +
  geom_bar(position = "dodge") +
  theme_bw()

# Or you can install themes that other people have created, like these at ggthemes: 
# https://yutannihilation.github.io/allYourFigureAreBelongToUs/ggthemes/
library(ggthemes)

ggplot(mpg, aes(x = drv, fill = factor(year))) +
  geom_bar(position = "dodge") +
  theme_fivethirtyeight()

ggplot(mpg, aes(x = drv, fill = factor(year))) +
  geom_bar(position = "dodge") +
  theme_economist()

ggplot(mpg, aes(x = drv, fill = factor(year))) +
  geom_bar(position = "dodge") +
  theme_stata()

# There are lots of others too, like these:
# https://github.com/MatthewBJane/theme_park
theme_name = "theme_barbie" # Pick which theme you want
theme_url = paste0("https://raw.githubusercontent.com/MatthewBJane/theme_park/main/", theme_name ,".R")
devtools::source_url(theme_url)

ggplot(mpg, aes(x = drv, fill = factor(year))) +
  geom_bar(position = "dodge") +
  theme_barbie()

Created on 2023-07-28 with reprex v2.0.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment