custom ggplot2 theme code for BURN meetup
# setup: example data | |
library(ggplot2) | |
library(data.table) | |
dt <- data.table( | |
period = c("before", "after", "before", "after"), | |
segment = c("treatment", "treatment", "control", "control"), | |
revenue = c(80, 85, 78, 79) | |
) | |
dt$period <- factor(dt$period, levels = c("before", "after")) | |
# base plot | |
our_ggplot <- ggplot(dt, aes(period, revenue, fill = segment)) + | |
geom_col(position = "dodge") + | |
geom_label( | |
aes(label = revenue), | |
position = position_dodge(width = 0.9) | |
) | |
# manual theme | |
our_ggplot + | |
scale_fill_manual(values = c("treatment" = "#377EB8", | |
"control" = "#E41A1C")) + | |
geom_label( | |
aes(label = revenue), | |
position = position_dodge(width = 0.9), | |
family = "Canaro Medium" | |
) + | |
theme_bw(base_family = "Canaro Medium") + | |
theme(legend.position = "bottom") | |
# set custom theme globally | |
get_theme_palette <- function() { | |
ggthemr::define_palette( | |
swatch = c("#000000", | |
"#377EB8", "#E41A1C", "#4DAF4A", "#984EA3", | |
"#FF7F00", "#FFFF33", "#A65628", "#F781BF"), | |
gradient = c(lower = "#377EB8", upper = "#E41A1C") | |
) | |
} | |
update_font_defaults <- function() { | |
update_geom_defaults("text", list(family = "Canaro Medium")) | |
update_geom_defaults("label", list(family = "Canaro Medium")) | |
} | |
theme_our <- function(base_size = 13) { | |
theme_bw(base_size, base_family = "Canaro Medium") + | |
theme(legend.position = "bottom") | |
} | |
set_our_theme <- function(base_size = 13) { | |
ggthemr::ggthemr(get_theme_palette()) | |
theme_set(theme_our(base_size = base_size)) | |
update_font_defaults() | |
} | |
set_our_theme() | |
# demonstrate usage | |
our_ggplot | |
ggplot(data.table(x = as.character(1:7), y = 1), aes(x, y, fill = x)) + | |
geom_col() | |
ggplot(data.table(x = 1:100, y = 1), aes(x, y, fill = x)) + | |
geom_col() | |
boxplot_dt <- data.table( | |
period = c(rep("before", 500), rep("after", 500)), | |
daily_revenue = c(rnorm(500, 20, 5), rnorm(500, 23, 5)) | |
) | |
boxplot_dt$period <- factor(boxplot_dt$period, levels = c("before", "after")) | |
ggplot(boxplot_dt, aes(x = period, y = daily_revenue, fill = period)) + | |
geom_boxplot() + | |
expand_limits(y = 0) + | |
theme(legend.position = "none") + | |
labs(x = NULL) | |
# reset | |
ggthemr::ggthemr_reset() | |
our_ggplot |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment