Skip to content

Instantly share code, notes, and snippets.

@rcatlord
Last active October 17, 2022 15:04
Show Gist options
  • Save rcatlord/e3a22df3bb58b77cb3588166457228a0 to your computer and use it in GitHub Desktop.
Save rcatlord/e3a22df3bb58b77cb3588166457228a0 to your computer and use it in GitHub Desktop.
theme_ONS
# load packages
library(ggplot2) ; library(showtext)
# add Google font
font_add_google("Open Sans")
showtext_auto()
# ggsave scaling issue: https://community.rstudio.com/t/font-gets-really-small-when-saving-to-png-using-ggsave-and-showtext/147029/6
showtext_opts(dpi = 300)
# load ONS theme
source("theme_ONS.R")
# plot
ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(colour = factor(cyl))) +
labs(
x = "Engine displacement (litres)",
y = "Highway miles per gallon",
colour = "Number of cylinders",
title = "Mileage by engine size and cylinders",
subtitle = "Source: http://fueleconomy.gov"
) +
theme_ONS() +
theme(panel.grid.major.x = element_line(color = "#D9D9D9"))
# save as PNG
ggsave("figure1.png")
theme_ONS <- function () {
theme_grey(base_size = 14, base_family = "Open Sans") %+replace%
theme(
# plot margin
plot.margin = unit(rep(0.5, 4), "cm"),
# plot background and border
plot.background = element_blank(),
panel.background = element_blank(),
panel.border = element_blank(),
# grid lines
panel.grid.major.x = element_blank(),
panel.grid.major.y = element_line(color = "#D9D9D9"),
panel.grid.minor = element_blank(),
# axis ticks and lines
axis.ticks.x = element_line(colour = "#D9D9D9"),
axis.ticks.y = element_line(colour = "#D9D9D9"),
axis.ticks.length.x = grid::unit(6, "pt"),
axis.line = element_blank(),
# title, subtitle and caption
plot.title = element_text(size = 18, face = "bold", colour = "#222222", hjust = 0),
plot.subtitle = element_text(size = 16, colour = "#222222", hjust = 0, margin = margin(8, 0, 30, 0)),
plot.caption = element_text(size = 16, face = "bold", color = "#222222", hjust = 0),
# axes titles
axis.title.x = element_text(colour = "#707071", hjust = 1, margin = margin(t = 10)),
axis.title.y = element_text(colour = "#707071", angle = 90, hjust = 1, margin = margin(r = 10)), # angle = 0, vjust = 1
axis.text.x = element_text(size = 14, colour = "#707071", margin = margin(t = 3)),
axis.text.y = element_text(size = 14, colour = "#707071"),
# legend
legend.position = "top",
legend.justification = "left",
legend.direction = "horizontal",
legend.text.align = 0,
legend.margin = margin(c(0,0,4,-6)/72, unit = "in"),
legend.background = element_blank(),
legend.title = element_blank(),
legend.key = element_blank(),
legend.text = element_text(size = 12, colour = "#414042"),
# facetting
strip.background = element_rect(fill = "transparent", colour = NA),
strip.text = element_text(size = 15, face = "bold", hjust = 0)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment