R/aec_ec_primary_focus_plot.R

Defines functions aec_ec_source_plot

Documented in aec_ec_source_plot

#' Plot the most likely primary focus for E. coli bacteraemia by time to onset
#'
#' Although the function takes a single argument (a data frame),
#' it relies on the presence of several variables to that data frame:
#' * \code{tto_group} The grouped time to onset, generated by \code{\link{group_tto_bacteraemia}}
#' * \code{primary_focus} One of the primary foci in \code{\link{group_source_bacteraemia}}
#' * \code{pc} The percentage that the focus occurs within tto_group
#' @param x A data frame
#' @return A ggplot2 object
#' @seealso \code{\link{group_tto_bacteraemia}} \code{\link{group_source_bacteraemia}}
#' @examples
#' \dontrun{
#' dat <- structure(list(
#' tto_group = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
#' 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L),
#' .Label = c("<2", "2-6", "ge7"), class = "factor"),
#' primary_focus = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 1L,
#' 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L),
#' .Label = c("gastro", "hepatobil", "other", "respiratory", "unknown", "uti"),
#' class = "factor"),
#' pc = c(20, 20, 20, 20, 10, 10,
#' 30, 20, 10, 10, 10, 20, 50, 10, 10, 10, 10,
#' 10)), .Names = c("tto_group", "primary_focus", "pc"),
#' class = "data.frame", row.names = c(NA, -18L))
#'
#' pal <- phecharts::brewer_phe("phe", length(levels(dat$primary_focus)))
#'
#' p <- aec_ec_source_plot(dat)
#' p
#' }
#' @export

aec_ec_source_plot <- function(x){
  if (!requireNamespace("ggplot2", quietly = TRUE)) {
    stop("ggplot2 needed for this function to work. Please install it.",
         call. = FALSE)
  }
  assertthat::assert_that(is.factor(x$primary_focus), msg = "primary_focus must be a factor")

  cc <- scales::seq_gradient_pal(low = "#08519C", high = "#C6DBEF", space = "Lab")((unique(as.numeric(x$primary_focus)))/length(levels(x$primary_focus)))

  ggplot2::ggplot(x, ggplot2::aes(x = tto_group, y = pc, group = tto_group,
                        fill = primary_focus)
  ) +
    ggplot2::geom_bar(stat = "identity") +
    #facet_wrap(~tto_group) +
    ggplot2::scale_x_discrete("Days between admission and positive specimen",
                              labels = c("<2", "2-6", "\u2265 7")) +
    ggplot2::scale_y_continuous("Percent cases") +
    # ggplot2::theme(axis.ticks = element_blank(), axis.text.x = element_blank()) +
    # scale_fill_discrete("Primary focus\n of infection")
    ggplot2::scale_fill_manual(
      "Primary focus\nof infection",
      values = cc,
      guide = ggplot2::guide_legend(reverse = TRUE)) +
    cowplot::theme_cowplot()
}
PublicHealthEngland/hcaidcs documentation built on Jan. 19, 2024, 8:38 a.m.