Hi all!
I’m pasting in some example code to create a custom ggplot function.
This example creates different epicurves using the Ebola linelist from Applied Epi’s introcourse.
It allows you to define all the formatting and details within theme() and scale_fill_manual() etc once time in the function, and then run very simple code to actually create the plots.
It also defines colour palettes within the function - which of course would need adding to if further epicurves are made with other breakdowns.
# 1) Define the custom plot function-----------------------------
epicurve <- function(data, xvalue, fillvalue) {
ggplot(data) +
geom_histogram(aes(x = {{xvalue}}, fill = {{fillvalue}}),
color = "white",
bin.width = 7) +
theme_minimal(base_size = 10) +
theme(
panel.background = element_rect(fill = "white", color = NA),
panel.grid.major = element_line(color = "gray", linetype = "dotted"),
panel.grid.minor = element_blank(),
axis.text.x = element_text(angle = 90, size = 8, hjust = 0, vjust = 0.5),
) +
scale_fill_manual(values = c(
#Hospital
"Central Hospital" = "#a6cee3",
"Military Hospital" = "#1f78b4",
"SMMH" = "#b2df8a",
"Port Hospital" = "#33a02c",
"Other" = "#fb9a99",
# Sex
"Female" = "seagreen",
"Male" = "navy",
# District
"Central I" = "#A8D5BA",
"Central II" = "#fdb462",
"East I" = "#FFE5B4",
"East II" = "#fb8072",
"East III" = "#C4D69B",
"Mountain Rural" = "#B2ABD2",
"West I" = "#D4C4A8",
"West II" = "#BCC1C9",
"West III" = "#1f78b4"
)) +
scale_y_continuous(expand = c(0, 0)) +
scale_x_date(
date_breaks = "14 days", # Monthly ticks
date_labels = "%d %b %y" # Format as "Jan 2021", "Feb 2021", etc.
) +
labs(y = "Weekly count")
}
# 2) Use the custom function for several plots ---------------
# Epicurve by onset date, stacked by district of residence of the case
epicurve(linelist, xvalue = OnsetDate, fillvalue = District)
# Epicurve by onset date, stacked by sex of case
epicurve(linelist, xvalue = OnsetDate, fillvalue = Sex)
# Epicurve by report date, stacked by hospital
epicurve(linelist, xvalue = ReportDate, fillvalue = Hospital)
The output is this: