### Diverging Bar Chart with Totals and Nudged Labels Source: https://ggsurveillance.biostats.dev/reference/geom_bar_diverging.html This example shows a diverging bar chart displaying totals by direction and nudging labels outward. It uses the same data setup as the basic example but modifies `stat_diverging()` to include `totals_by_direction = TRUE` and `nudge_label_outward = 0.05` for enhanced label positioning. ```R ggplot(df_6cat, aes(y = name, fill = value)) + geom_bar_diverging() + # Bars stat_diverging(totals_by_direction = TRUE, nudge_label_outward = 0.05) + # Totals as Label scale_x_continuous_diverging() + # Scale theme_classic() ``` -------------------------------- ### Load linelist_hospital_outbreak dataset Source: https://ggsurveillance.biostats.dev/reference/linelist_hospital_outbreak.html This code snippet shows how to load the `linelist_hospital_outbreak` dataset. No specific setup or imports are required beyond base R. ```r linelist_hospital_outbreak ``` -------------------------------- ### Epicurve with vertical lines at week breaks Source: https://ggsurveillance.biostats.dev/reference/geom_vline_year.html This example shows an epicurve plot with vertical lines marking the beginning of each week. The 'week' break type is specified, placing lines at the start of each ISO week. ```r ggplot(plot_data_epicurve_imp, aes(x = date, weight = 2)) + geom_epicurve(date_resolution = "week") + geom_vline_year(break_type = "week") + labs(title = "Epicurve Example") + scale_y_cases_5er() + scale_x_date(date_breaks = "4 weeks", date_labels = "W%V'%g") + # Correct ISOWeek labels week'year theme_bw() ``` -------------------------------- ### Basic geom_col_range example Source: https://ggsurveillance.biostats.dev/reference/geom_col_range.html This example demonstrates the basic usage of geom_col_range to create a bar chart with specified ymin and ymax values. Ensure the ggplot2 library is loaded and data is provided with x, ymin, and ymax aesthetics. ```R library(ggplot2) df <- data.frame(x = 1:3, ymin = -1:-3, ymax = 1:3) ggplot(df, aes(x = x, ymin = ymin, ymax = ymax)) + geom_col_range() ``` -------------------------------- ### ISO Week Binning with Formatted Dates Source: https://ggsurveillance.biostats.dev/reference/bin_by_date.html Aggregates data into ISO weeks (Monday start) using `date_resolution = "isoweek"`. It then formats the `onset_date` to display the ISO week number for clearer labeling. ```r bin_by_date(outbreak_data, onset_date, date_resolution = "isoweek" ) |> mutate(date_formatted = strftime(onset_date, "%G-W%V")) # Add correct date labels ``` -------------------------------- ### Epicurve with vertical lines at day breaks Source: https://ggsurveillance.biostats.dev/reference/geom_vline_year.html This example demonstrates adding vertical lines at the start of each year to an epicurve plot. The default 'day' break type is used, with lines placed at January 1st of each year. ```r library(ggplot2) set.seed(1) plot_data_epicurve_imp <- data.frame( date = rep(as.Date("2023-12-01") + ((0:300) * 1), times = rpois(301, 0.5)) ) # Break type day ggplot(plot_data_epicurve_imp, aes(x = date, weight = 2)) + geom_epicurve(date_resolution = "week") + geom_vline_year() + labs(title = "Epicurve Example") + scale_y_cases_5er() + scale_x_date(date_breaks = "4 weeks", date_labels = "W%V'%g") + # Correct ISOWeek labels week'year theme_bw() ``` -------------------------------- ### Create Epi Gantt Chart with Stays and Detections Source: https://ggsurveillance.biostats.dev/reference/geom_epigantt.html This example demonstrates how to create an Epi Gantt chart using transformed hospital outbreak data. It visualizes patient ward stays as colored bars and pathogen detection dates as points, using ggplot2 with ggsurveillance. ```R library(dplyr) library(tidyr) library(ggplot2) # Transform hospital outbreak line list to long format linelist_hospital_outbreak | pivot_longer( cols = starts_with("ward"), names_to = c(".value", "num"), names_pattern = "ward_(name|start_of_stay|end_of_stay)_([0-9]+)", values_drop_na = TRUE ) -> df_stays_long linelist_hospital_outbreak | pivot_longer(cols = starts_with("pathogen"), values_to = "date") -> df_detections_long # Create Epi Gantt chart showing ward stays and test dates ggplot(df_stays_long) + geom_epigantt(aes(y = Patient, xmin = start_of_stay, xmax = end_of_stay, color = name)) + geom_point(aes(y = Patient, x = date, shape = "Date of pathogen detection"), data = df_detections_long ) + scale_y_discrete_reverse() + theme_bw() + theme_mod_legend_bottom() #> Warning: Removed 7 rows containing missing values or values outside the scale range #> (`geom_point()`). ``` -------------------------------- ### Create an epicurve with geom_epicurve Source: https://ggsurveillance.biostats.dev/reference/geom_epicurve.html This example demonstrates how to create a basic epicurve using the SARS dataset. It pivots the data to long format and then uses geom_epicurve to plot the cases by week. Ensure the 'tidyr' and 'outbreaks' libraries are loaded. ```R library(tidyr) library(outbreaks) sars_canada_2003 |> # SARS dataset from outbreaks pivot_longer(starts_with("cases"), names_prefix = "cases_", names_to = "origin") |> ggplot(aes(x = date, weight = value, fill = origin)) + geom_epicurve(date_resolution = "week") + scale_x_date(date_labels = "W%V'%g", date_breaks = "2 weeks") + scale_y_cases_5er() + theme_classic() ``` -------------------------------- ### Seasonal Visualization with Aligned Data Source: https://ggsurveillance.biostats.dev/reference/align_dates_seasonal.html Example of visualizing aligned influenza data using ggplot2. Aligns data by ReportingWeek to 'epiweek' resolution with a season start of week 28, then plots Incidence by aligned date, faceted by AgeGroup. ```R # Seasonal Visualization of Germany Influenza Surveillance Data library(ggplot2) influenza_germany | align_dates_seasonal( dates_from = ReportingWeek, date_resolution = "epiweek", start = 28 ) -> df_flu_aligned ggplot(df_flu_aligned, aes(x = date_aligned, y = Incidence, color = season)) + geom_line() + facet_wrap(~AgeGroup) + theme_bw() + theme_mod_rotate_x_axis_labels_45() ``` -------------------------------- ### Nested Datetime Axis with Fence Type Source: https://ggsurveillance.biostats.dev/reference/guide_axis_nested_date.html Applies a nested date axis guide to a datetime scale using the 'fence' type. Labels show hours and day-month. ```R datetime_data <- data.frame( datetime = rep(as.POSIXct("2024-02-05 01:00:00") + 0:50 * 3600, times = rpois(51, 3) ) ) ggplot(datetime_data, aes(x = datetime)) + geom_epicurve(date_resolution = "2 hours") + scale_x_datetime( date_breaks = "6 hours", date_labels = "%Hh %e.%b", limits = c(as.POSIXct("2024-02-04 22:00:00"), NA), guide = guide_axis_nested_date() ) ``` -------------------------------- ### Basic Diverging Bar Chart with Labels Source: https://ggsurveillance.biostats.dev/reference/geom_bar_diverging.html This example demonstrates a basic diverging bar chart with labels. It requires `ggplot2`, `dplyr`, and `tidyr` libraries. The data is structured to have 6 categories, and the bars and labels are plotted using `geom_bar_diverging()` and `stat_diverging()`, respectively. A diverging scale is applied using `scale_x_continuous_diverging()`. ```R library(ggplot2) library(dplyr) library(tidyr) set.seed(123) df_6cat <- data.frame(matrix(sample(1:6, 600, replace = TRUE), ncol = 6)) |> mutate_all(~ ordered(., labels = c("+++", "++", "+", "-", "--", "---"))) pivot_longer(cols = everything()) ggplot(df_6cat, aes(y = name, fill = value)) + geom_bar_diverging() + # Bars stat_diverging() + # Labels scale_x_continuous_diverging() + # Scale theme_classic() ``` -------------------------------- ### Basic Nested Date Axis Source: https://ggsurveillance.biostats.dev/reference/guide_axis_nested_date.html Applies a nested date axis guide to an epicurve plot with weekly resolution. Uses default settings for the nested axis. ```R library(ggplot2) # Create sample epidemic curve data epi_data <- data.frame( date = rep(as.Date("2023-12-15") + 0:100, times = rpois(101, 2)) ) ggplot(epi_data, aes(x = date)) + geom_epicurve(date_resolution = "week") + scale_x_date( date_breaks = "2 weeks", date_labels = "%d-%b-%Y", guide = guide_axis_nested_date() ) ``` -------------------------------- ### Apply custom y-axis scale to an epicurve plot Source: https://ggsurveillance.biostats.dev/reference/scale_y_cases_5er.html This example demonstrates applying the `scale_y_cases_5er()` to a ggplot object that uses `geom_epicurve`. It also includes `theme_mod_remove_minor_grid_y()` for plot customization. ```R library(ggplot2) data <- data.frame(date = as.Date("2024-01-01") + 0:30) ggplot(data, aes(x = date)) + geom_epicurve(date_resolution = "week") + scale_y_cases_5er() + theme_mod_remove_minor_grid_y() ``` -------------------------------- ### Concise Date Labelling with label_date_short Source: https://ggsurveillance.biostats.dev/reference/label_date.html This example shows the usage of `label_date_short()` for concise date labelling on the x-axis of a plot. It automatically adjusts the displayed date components based on changes, making the axis less cluttered. Requires `tidyr`, `outbreaks`, and `ggplot2`. ```R sars_canada_2003 |> # SARS dataset from outbreaks pivot_longer(starts_with("cases"), names_prefix = "cases_", names_to = "origin") |> ggplot(aes(x = date, weight = value, fill = origin)) + geom_epicurve(date_resolution = "week") + scale_x_date(labels = label_date_short(), date_breaks = "1 week") + scale_y_cases_5er() + theme_classic() ``` -------------------------------- ### Customizing Date Labels with Italian Locale Source: https://ggsurveillance.biostats.dev/reference/label_date.html This example demonstrates how to change the locale of date labels to Italian using `label_date` with the `locale = "it"` argument. It requires libraries like `tidyr`, `outbreaks`, and `ggplot2`. ```R library(tidyr) library(outbreaks) library(ggplot2) # Change locale of date labels to Italian sars_canada_2003 |> # SARS dataset from outbreaks pivot_longer(starts_with("cases"), names_prefix = "cases_", names_to = "origin") |> ggplot(aes(x = date, weight = value, fill = origin)) + geom_epicurve(date_resolution = "week") + scale_x_date(labels = label_date("%B %Y", locale = "it"), date_breaks = "1 month") + scale_y_cases_5er() + theme_classic() ``` -------------------------------- ### US CDC Epiweek Binning Source: https://ggsurveillance.biostats.dev/reference/bin_by_date.html Aggregates data into US CDC epiweeks (Sunday start) by setting `date_resolution` to 'epiweek'. This is commonly used for official public health reporting. ```r bin_by_date(outbreak_data, onset_date, date_resolution = "epiweek" ) ``` -------------------------------- ### Multiple Lines with Custom Labels and Repulsion Source: https://ggsurveillance.biostats.dev/reference/stat_last_value.html Annotate multiple time series lines with custom labels and use geom_label_last_value_repel for label placement. This example also demonstrates logarithmic y-axis and legend customization. Requires ggplot2 and potentially other theme/scale functions. ```r ggplot(economics_long, aes(x = date, y = value, color = variable)) + geom_line() + stat_last_value() + # Add a point at the end geom_label_last_value_repel(aes(label = variable), expand_rel = 0.1, nudge_rel = 0.05 ) + scale_y_log10() + theme_mod_disable_legend() ``` -------------------------------- ### Vaccination Status Visualization with geom_bar_diverging Source: https://ggsurveillance.biostats.dev/reference/geom_bar_diverging.html Visualize vaccination status proportions over years using geom_bar_diverging. This example demonstrates forcing a neutral category ('Unknown') and using proportions to show relative distributions. stat_diverging is used to add labels for proportions. ```R set.seed(456) cases_vacc <- data.frame(year = 2017:2025) |> rowwise() |> mutate(vacc = list(sample(1:4, 100, prob = (4:1)^(1 - 0.2 * (year - 2017)), replace = TRUE))) |> unnest(vacc) |> mutate( year = as.factor(year), "Vaccination Status" = ordered(vacc, labels = c("Fully Vaccinated", "Partially Vaccinated", "Unknown", "Unvaccinated") ) ) ggplot(cases_vacc, aes(y = year, fill = `Vaccination Status`)) + geom_vline(xintercept = 0) + geom_bar_diverging(proportion = TRUE, neutral_cat = "force", break_pos = "Unknown") + stat_diverging( size = 3, proportion = TRUE, neutral_cat = "force", break_pos = "Unknown", totals_by_direction = TRUE, nudge_label_outward = 0.05 ) + scale_x_continuous_diverging(labels = scales::label_percent(), n.breaks = 10) + scale_y_discrete_reverse() + ggtitle("Proportion of vaccinated cases by year") + theme_classic() + theme_mod_legend_bottom() ``` -------------------------------- ### Basic usage of label_power10 Source: https://ggsurveillance.biostats.dev/reference/label_power10.html Demonstrates the basic functionality of label_power10 with default settings, showing how it formats a vector of numbers into R expressions. ```R library(ggplot2) # Basic usage with default settings label_power10()(c(1000, 10000, 100000, -1000)) ``` -------------------------------- ### Basic Epicurve with Dates Source: https://ggsurveillance.biostats.dev/reference/geom_epicurve.html Demonstrates creating a basic epicurve using geom_epicurve with date aggregation by week. It includes essential ggplot2 components like labs, scales, and coordinate transformations for proper visualization. Use this for standard outbreak investigations. ```R library(ggplot2) set.seed(1) plot_data_epicurve_imp <- data.frame( date = rep(as.Date("2023-12-01") + ((0:300) * 1), times = rpois(301, 0.5)) ) ggplot(plot_data_epicurve_imp, aes(x = date, weight = 2)) + geom_vline_year(break_type = "week") + geom_epicurve(date_resolution = "week") + labs(title = "Epicurve Example") + scale_y_cases_5er() + # Correct ISOWeek labels for week-year scale_x_date(date_breaks = "4 weeks", date_labels = "W%V'%g") + coord_equal(ratio = 7) + # Use coord_equal for square boxes. 'ratio' are the days per week. theme_bw() ``` -------------------------------- ### Custom Formatting with Upper Bounds Source: https://ggsurveillance.biostats.dev/reference/create_agegroups.html Demonstrates custom formatting for age groups using upper bounds. The `interval_format` and `first_group_format` arguments allow for specific string representations of age ranges. ```r create_agegroups(1:100, breaks_as_lower_bound = FALSE, interval_format = "{x} to {y}", first_group_format = "0 to {x}" ) ``` -------------------------------- ### geom_epicurve_point Function Signature Source: https://ggsurveillance.biostats.dev/reference/geom_epicurve.html Adds points or shapes to cases on epicurve plots. Similar to geom_epicurve_text, it supports date resolution and week start options. ```R geom_epicurve_point( mapping = NULL, data = NULL, stat = "epicurve", vjust = 0.5, date_resolution = NULL, week_start = getOption("lubridate.week.start", 1), ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) ``` -------------------------------- ### Short Notice for Interactive Programs Source: https://ggsurveillance.biostats.dev/LICENSE.html This is a concise notice to be displayed by programs that interact via the terminal when they start. It informs users about the absence of warranty and the terms of redistribution. ```text Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. This is free software, and you are welcome to redistribute it under certain conditions; type 'show c' for details. ``` -------------------------------- ### Align and Bin Dates for Seasonal Comparison Source: https://ggsurveillance.biostats.dev/reference/align_dates_seasonal.html Convenience wrapper to align dates and then bin data for counts and incidence calculation. Supports specifying population and filling gaps. Useful for preparing data for incidence-based seasonal plots. ```R align_and_bin_dates_seasonal( x, dates_from, n = 1, population = 1, fill_gaps = FALSE, date_resolution = c("week", "isoweek", "epiweek", "day", "month"), start = NULL, target_year = NULL, drop_leap_week = TRUE, .groups = "drop" ) ``` -------------------------------- ### align_and_bin_dates_seasonal Source: https://ggsurveillance.biostats.dev/reference/align_dates_seasonal.html A convenience wrapper that first aligns the dates and then bins the data to calculate counts and incidence. ```APIDOC ## align_and_bin_dates_seasonal() ### Description A convenience wrapper that first aligns the dates and then bins the data to calculate counts and incidence. ### Arguments * `x`: Either a data frame with a date column, or a date vector. Supported date formats are `date` and `datetime` and also commonly used character strings: ISO dates "2024-03-09", Month "2024-03", Week "2024-W09" or "2024-W09-1". * `dates_from`: Column name containing the dates to align and bin. Used when x is a data.frame. * `n`: Numeric column with case counts (or weights). Supports quoted and unquoted column names. * `population`: A number or a numeric column with the population size. Used to calculate the incidence. * `fill_gaps`: Logical; If `TRUE`, gaps in the time series will be filled with 0 cases. Useful for ensuring complete time series without missing periods. Defaults to `FALSE`. * `date_resolution`: Character string specifying the temporal resolution. One of: "week" or "isoweek" - Calendar weeks (ISO 8601), epidemiological reporting weeks as used by the ECDC. "epiweek" - Epidemiological weeks as defined by the US CDC (weeks start on Sunday). "month" - Calendar months. "day" - Daily resolution. * `start`: Numeric value indicating epidemic season start, i.e. the start and end of the new year interval. For `week/epiweek`: week number (default: 28, approximately July). For `month`: month number (default: 7 for July). For `day`: day of year (default: 150, approximately June). If start is set to "1" the alignment is done for yearly comparison and the shift in dates for seasonality is skipped. * `target_year`: Numeric value for the reference year to align dates to. The default target year is the start of the most recent season in the data. This way the most recent dates stay unchanged. * `drop_leap_week`: If `TRUE` and date_resolution is `week`, `isoweek` or `epiweek`, leap weeks (week 53) are dropped if they are not in the most recent season. Set to `FALSE` to retain leap weeks from all seasons. Dropping week 53 from historical data is the most common approach. Otherwise historical data for week 53 would map to week 52 if the target season has no leap week, resulting in a doubling of the case counts. * `.groups`: See `dplyr::summarise()`. ### Value A data frame with standardized date columns: `year`: Calendar year from original date. `week/month/day`: Time unit based on chosen resolution. `date_aligned`: Date standardized to target year. `season`: Epidemic season identifier (e.g., "2023/24"), if `start = 1` this is the year only (e.g. 2023). `current_season`: Logical flag for most recent season. Binning also creates the columns: `n`: Sum of cases in bin. `incidence`: Incidence calculated using n/population. ### Details This function helps create standardized epidemic curves by aligning surveillance data from different years. This enables: Comparison of disease patterns across multiple seasons, Identification of typical seasonal trends, Detection of unusual disease activity, Assessment of current season against historical patterns. The alignment can be done at different temporal resolutions (daily, weekly, monthly) with customizable season start points to match different disease patterns or surveillance protocols. ``` -------------------------------- ### stat_bin_date Function Signature Source: https://ggsurveillance.biostats.dev/reference/geom_epicurve.html Provides date-based binning of observations, behaving like ggplot2::stat_count after binning. Supports various date resolutions and week start configurations. ```R stat_bin_date( mapping = NULL, data = NULL, geom = "line", position = "identity", date_resolution = NULL, week_start = getOption("lubridate.week.start", 1), fill_gaps = FALSE, ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) ``` -------------------------------- ### Monthly Binning Source: https://ggsurveillance.biostats.dev/reference/bin_by_date.html Aggregates data into monthly bins by setting `date_resolution` to 'month'. This is useful for observing trends over longer periods. ```r bin_by_date(outbreak_data, onset_date, date_resolution = "month" ) ``` -------------------------------- ### Weekly Binning with Case Weights Source: https://ggsurveillance.biostats.dev/reference/bin_by_date.html Aggregates data into weekly bins using case counts as weights for incidence calculation. This is the default behavior when no specific date resolution is provided. ```r bin_by_date(outbreak_data, onset_date, n = cases) ``` -------------------------------- ### Standard GNU GPL Copyright Notice Source: https://ggsurveillance.biostats.dev/LICENSE.html This is the standard notice to be attached to the start of each source file when distributing a program under the GNU GPL. It includes copyright information and a reference to the full license. ```text Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ``` -------------------------------- ### Define X-axis scale for case counts Source: https://ggsurveillance.biostats.dev/reference/scale_y_cases_5er.html Use `scale_x_cases_5er()` for a continuous x-axis scale with optimized breaks for count data. It ensures the scale starts at 0 and prefers '5er' breaks. ```R scale_x_cases_5er( name = waiver(), n = 8, min.n = 5, u5.bias = 4, expand = NULL, limits = c(0, NA), labels = waiver(), oob = scales::censor, na.value = NA_real_, transform = "identity", position = "bottom", sec.axis = waiver(), guide = waiver(), ... ) ``` -------------------------------- ### Define Y-axis scale for case counts Source: https://ggsurveillance.biostats.dev/reference/scale_y_cases_5er.html Use `scale_y_cases_5er()` for a continuous y-axis scale with optimized breaks for count data. It ensures the scale starts at 0 and prefers '5er' breaks. ```R scale_y_cases_5er( name = waiver(), n = 8, min.n = 5, u5.bias = 4, expand = NULL, limits = c(0, NA), labels = waiver(), oob = scales::censor, na.value = NA_real_, transform = "identity", position = "left", sec.axis = waiver(), guide = waiver(), ... ) ``` -------------------------------- ### Collapsing Single Year Groups Source: https://ggsurveillance.biostats.dev/reference/create_agegroups.html Illustrates how to collapse single-year age groups into broader ranges when specified. This is useful for simplifying age distributions, especially for younger age cohorts. ```r create_agegroups(1:10, age_breaks = c(1, 2, 3, 4, 5, 10), collapse_single_year_groups = TRUE ) ``` -------------------------------- ### bin_by_date Source: https://ggsurveillance.biostats.dev/reference/bin_by_date.html Aggregates data by specified time periods and calculates incidence rates. ```APIDOC ## bin_by_date ### Description Aggregates data by specified time periods (e.g., weeks, months) and calculates (weighted) counts. Incidence rates are also calculated using the provided population numbers. This function is the core date binning engine used by `geom_epicurve()` and `stat_bin_date()` for creating epidemiological time series visualizations. ### Usage ```R bin_by_date( x, dates_from, n = 1, population = 1, fill_gaps = FALSE, date_resolution = "week", week_start = 1, .groups = "drop" ) ``` ### Arguments * `x` (data frame or date vector): Data to be binned. Supports date, datetime, and character strings (ISO dates, Month, Week). * `dates_from` (column name): Column containing the dates to bin (used when `x` is a data frame). * `n` (numeric column): Case counts or weights. Supports quoted and unquoted column names. * `population` (number or numeric column): Population size for incidence calculation. * `fill_gaps` (logical): If `TRUE`, fills missing time periods with 0 cases. Defaults to `FALSE`. * `date_resolution` (character string): Time unit for aggregation. Options include: `"hour"`, `"day"`, `"week"`, `"month"`, `"bimonth"`, `"season"`, `"quarter"`, `"halfyear"`, `"year"`, `"isoweek"`, `"epiweek"`, `"isoyear"`, `"epiyear"`. Defaults to `"week"`. * `week_start` (integer): Start of the week (1 = Monday, 7 = Sunday). Only used when `date_resolution` involves weeks. Defaults to 1. Overridden by `"isoweek"` (1) and `"epiweek"` (7). * `.groups` (character string): See `dplyr::summarise()`. ### Value A data frame with the following columns: * A date column (same name as `dates_from`) binned to the specified time period. * `n`: Sum of weights (case counts) for each time period. * `incidence`: Incidence rate (`n / population`) for each time period. * Preserves any existing grouping variables. ### Details The function performs date coercion, optional gap filling, date binning using `lubridate::floor_date()`, and aggregation of counts and incidence rates. ### Examples ```R library(dplyr) # Create sample data outbreak_data <- data.frame( onset_date = as.Date("2024-12-10") + sample(0:100, 50, replace = TRUE), cases = sample(1:5, 50, replace = TRUE) ) # Basic weekly binning bin_by_date(outbreak_data, dates_from = onset_date) ``` ``` -------------------------------- ### Transform Linelist to Long Format for Stays Source: https://ggsurveillance.biostats.dev/articles/Epigantt_with_ggsurveillance.html Transforms the wide-format linelist data into a long format suitable for ggplot, extracting ward names, start, and end dates. This is a prerequisite for plotting with geom_epigantt. ```r linelist_hospital_outbreak | pivot_longer( cols = starts_with("ward"), names_to = c(".value", "num"), names_pattern = "ward_(name|start_of_stay|end_of_stay)_([0-9]+)", values_drop_na = TRUE ) -> df_stays_long df_stays_long |> select(Patient, num:end_of_stay) #> # A tibble: 9 × 5 #> Patient num name start_of_stay end_of_stay #> #> 1 0 1 intensive care unit 2024-06-12 2024-07-25 #> 2 1 1 intensive care unit 2024-06-26 2024-07-03 #> 3 2 1 intensive care unit 2024-06-28 2024-07-06 #> 4 3 1 intensive care unit 2024-06-19 2024-06-26 #> 5 3 2 general ward 2024-06-26 2024-07-13 #> 6 4 1 general ward 2024-07-03 2024-07-12 #> 7 5 1 general ward 2024-07-04 2024-07-15 #> 8 6 1 general ward 2024-07-06 2024-07-11 #> 9 7 1 general ward 2024-06-30 2024-07-05 ``` -------------------------------- ### Access German States Population Data Source: https://ggsurveillance.biostats.dev/reference/population_german_states.html This snippet shows how to access the `population_german_states` dataset. No specific imports are required as it's a loaded dataset. ```r population_german_states ``` -------------------------------- ### Align Dates for Seasonal Comparison Source: https://ggsurveillance.biostats.dev/reference/align_dates_seasonal.html Aligns dates from multiple years to a common reference for seasonal comparison. Specify date resolution and season start. Useful for comparing disease patterns across seasons. ```R align_dates_seasonal( x, dates_from = NULL, date_resolution = c("week", "isoweek", "epiweek", "day", "month"), start = NULL, target_year = NULL, drop_leap_week = TRUE ) ``` -------------------------------- ### Create Epigantt Plots for Outbreak Visualization Source: https://ggsurveillance.biostats.dev/index.html Generates an Epigantt plot to visualize exposure intervals in outbreaks. Requires 'dplyr', 'tidyr', 'ggplot2', and 'ggsurveillance'. Transforms linelist data into long format for plotting. ```R library(dplyr) library(tidyr) library(ggplot2) library(ggsurveillance) # Transform to long format linelist_hospital_outbreak |> pivot_longer( cols = starts_with("ward"), names_to = c(".value", "num"), names_pattern = "ward_(name|start_of_stay|end_of_stay)_([0-9]+)", values_drop_na = TRUE ) -> df_stays_long linelist_hospital_outbreak |> pivot_longer(cols = starts_with("pathogen"), values_to = "date") -> df_detections_long # Plot ggplot(df_stays_long) + geom_epigantt(aes(y = Patient, xmin = start_of_stay, xmax = end_of_stay, color = name)) + geom_point(aes(y = Patient, x = date, shape = "Date of pathogen detection"), data = df_detections_long) + scale_y_discrete_reverse() + theme_bw() + theme_mod_legend_bottom() ``` -------------------------------- ### Diverging Continuous Scale Usage Source: https://ggsurveillance.biostats.dev/reference/scale_continuous_diverging.html Demonstrates the basic usage of `scale_x_continuous_diverging` and `scale_y_continuous_diverging` with sample data. These scales automatically create symmetrical limits around zero. ```r library(ggplot2) # Create sample data with positive and negative values df <- data.frame( x = c(-5, -2, 0, 3, 7), y = c(2, -1, 0, -3, 5) ) # Basic usage ggplot(df, aes(x, y)) + geom_point() + scale_x_continuous_diverging() + scale_y_continuous_diverging() ``` -------------------------------- ### Plot EpiGantt Chart with Detections Source: https://ggsurveillance.biostats.dev/articles/Epigantt_with_ggsurveillance.html Generates an EpiGantt chart using geom_epigantt for patient stays and adds points for pathogen detection dates using geom_point. Requires data to be in long format. ```r ggplot(df_stays_long) + geom_epigantt(aes(y = Patient, xmin = start_of_stay, xmax = end_of_stay, color = name)) + geom_point(aes(y = Patient, x = date, shape = "Date of pathogen detection"), data = df_detections_long) + scale_y_discrete_reverse() + theme_bw() + theme_mod_legend_bottom() ``` -------------------------------- ### Skip date labels with custom format Source: https://ggsurveillance.biostats.dev/reference/label_skip.html Skips date labels on the x-axis while preserving the major ticks, using a custom date format. The `start = "right"` argument ensures the skipping pattern begins from the last tick, and `labeller = label_date()` formats the remaining labels. ```r library(ggplot2) # Skip date labels, while keep ticks ggplot(economics, aes(x = date, y = unemploy)) + geom_line() + scale_x_date( date_breaks = "2 years", labels = label_skip(start = "right", labeller = label_date(format = "%Y")) ) + theme_bw() ``` -------------------------------- ### Load influenza_germany dataset Source: https://ggsurveillance.biostats.dev/reference/influenza_germany.html This code snippet shows how to load the influenza_germany dataset. It is a data frame containing weekly influenza case counts and incidence. ```r influenza_germany ``` -------------------------------- ### Create a Seasonal Plot with Historical Median and Current Season Source: https://ggsurveillance.biostats.dev/articles/align_dates_seasonal.html Generates a seasonal plot for a specific age group ('00+'), showing the historical median incidence with a ribbon and highlighting the current season's incidence with a thicker line. Requires `ggplot2` and data filtered for the current season. ```r influenza_germany | filter(AgeGroup == "00+") | align_dates_seasonal( dates_from = ReportingWeek, date_resolution = "isoweek", start = 28 ) -> df_flu_aligned ggplot(df_flu_aligned, aes(x = date_aligned, y = Incidence)) + stat_summary( aes(linetype = "Historical Median (Min-Max)"), data = . %>% filter(!current_season), fun.data = median_hilow, geom = "ribbon", alpha = 0.3 ) + stat_summary( aes(linetype = "Historical Median (Min-Max)"), data = . %>% filter(!current_season), fun = median, geom = "line" ) + geom_line( aes(linetype = "2024/25"), data = . %>% filter(current_season), colour = "dodgerblue4", linewidth = 2 ) + labs(linetype = "") + scale_x_date(date_labels = "%b'%y") + theme_bw() + theme(legend.position = c(0.2, 0.8)) ``` -------------------------------- ### scale_y_discrete_reverse() and scale_x_discrete_reverse() Source: https://ggsurveillance.biostats.dev/reference/scale_y_discrete_reverse.html These functions provide reversed discrete scales for the y-axis and x-axis respectively. They are useful when you want the first factor level to appear at the top (for y-axis) or left (for x-axis) of the plot, or to sort factors alphabetically from Z to A. ```APIDOC ## scale_y_discrete_reverse() ### Description Reversed discrete scale for the y-axis. ### Usage ```R scale_y_discrete_reverse( name = waiver(), limits = NULL, ..., expand = waiver(), position = "left" ) ``` ### Arguments * `name` (character or waiver) - The name of the scale. Used as the axis or legend title. If `waiver()`, the default, the name of the scale is taken from the first mapping used for that aesthetic. If `NULL`, the legend title will be omitted. * `limits` (NULL or character vector) - Can be either NULL which uses the default reversed scale values or a character vector which will be reversed. * `...` - Arguments passed on to `ggplot2::discrete_scale()`. * `expand` (waiver or expansion) - For position scales, a vector of range expansion constants used to add some padding around the data to ensure that they are placed some distance away from the axes. Use the convenience function `expansion()` to generate the values for the `expand` argument. The defaults are to expand the scale by 5% on each side for continuous variables, and by 0.6 units on each side for discrete variables. * `position` (character) - The position of the axis. `left` or `right` for y axes. ### Value A `ggplot2` scale object that can be added to a plot. ### See also `geom_epigantt()`, `ggplot2::scale_y_discrete()` ### Example ```R library(ggplot2) # Create sample data df <- data.frame( category = factor(c("A", "B", "C", "D")), value = c(10, 5, 8, 3) ) # Basic plot with reversed y-axis ggplot(df, aes(x = value, y = category)) + geom_col() + scale_y_discrete_reverse() ``` ## scale_x_discrete_reverse() ### Description Reversed discrete scale for the x-axis. ### Usage ```R scale_x_discrete_reverse( name = waiver(), limits = NULL, ..., expand = waiver(), position = "bottom" ) ``` ### Arguments * `name` (character or waiver) - The name of the scale. Used as the axis or legend title. If `waiver()`, the default, the name of the scale is taken from the first mapping used for that aesthetic. If `NULL`, the legend title will be omitted. * `limits` (NULL or character vector) - Can be either NULL which uses the default reversed scale values or a character vector which will be reversed. * `...` - Arguments passed on to `ggplot2::discrete_scale()`. * `expand` (waiver or expansion) - For position scales, a vector of range expansion constants used to add some padding around the data to ensure that they are placed some distance away from the axes. Use the convenience function `expansion()` to generate the values for the `expand` argument. The defaults are to expand the scale by 5% on each side for continuous variables, and by 0.6 units on each side for discrete variables. * `position` (character) - The position of the axis. `top` or `bottom` for x axes. ### Value A `ggplot2` scale object that can be added to a plot. ### See also `geom_epigantt()`, `ggplot2::scale_x_discrete()` ``` -------------------------------- ### Aggregate data by time periods using bin_by_date Source: https://ggsurveillance.biostats.dev/reference/bin_by_date.html Aggregates data by specified time periods (e.g., weeks, months) and calculates incidence rates. Use this function for core date binning in epidemiological time series visualizations. ```R library(dplyr) #> #> Attaching package: ‘dplyr’ #> The following objects are masked from ‘package:stats’: #> #> filter, lag #> The following objects are masked from ‘package:base’: #> #> intersect, setdiff, setequal, union # Create sample data outbreak_data <- data.frame( onset_date = as.Date("2024-12-10") + sample(0:100, 50, replace = TRUE), cases = sample(1:5, 50, replace = TRUE) ) # Basic weekly binning bin_by_date(outbreak_data, dates_from = onset_date) #> # A tibble: 15 × 3 #> onset_date n incidence #> #> 1 2024-12-09 5 5 #> 2 2024-12-16 3 3 #> 3 2024-12-23 1 1 #> 4 2024-12-30 4 4 #> 5 2025-01-06 7 7 #> 6 2025-01-13 1 1 #> 7 2025-01-20 6 6 #> 8 2025-01-27 3 3 #> 9 2025-02-03 4 4 #> 10 2025-02-10 4 4 #> 11 2025-02-17 5 5 #> 12 2025-02-24 2 2 #> 13 2025-03-03 3 3 #> 14 2025-03-10 1 1 #> 15 2025-03-17 1 1 ``` -------------------------------- ### Date Labeller Function Signatures Source: https://ggsurveillance.biostats.dev/reference/label_date.html These are the function signatures for `label_date` and `label_date_short`. `label_date` formats dates with a specified format, timezone, and locale. `label_date_short` provides a more concise labelling, only showing components when they change. ```R label_date(format = "%Y-%m-%d", tz = "UTC", locale = NULL) label_date_short( format = c("%Y", "%b", "%d", "%H:%M"), sep = "\n", leading = "0", tz = "UTC", locale = NULL ) ``` -------------------------------- ### Incidence Calculation with Population Data Source: https://ggsurveillance.biostats.dev/reference/bin_by_date.html Calculates incidence rates by providing population data. The `population` argument allows for the normalization of case counts against a defined population size. ```r outbreak_data$population <- 10000 bin_by_date(outbreak_data, onset_date, n = cases, population = population ) ```