R/mod_indel_distribution_fct.R

Defines functions indel_species_plot truncate_numeric

truncate_numeric <- function(vector, cut_points) {
  vector[vector < cut_points[[1]]] <- cut_points[[1]] - 1
  vector[vector > cut_points[[2]]] <- cut_points[[2]] + 1
  vector
}

indel_species_plot <-
  function(.data,
           .gvar,
           .fvar,
           .cut_points,
           .title = "Indel species distribution",
           .xlab = "Indel species distribution (in bp)",
           .ylab = "% Editing",
           .dims = c(500, 500)
           ) {

    shiny::validate(shiny::need(
      checkmate::test_subset(c(.gvar, .fvar), c(colnames(.data), "none")),
      message = "A selected configuration variable is not among the columns in the data for this project. Please choose another option."
    ))

    if (!is.null(.gvar) & !.gvar == "none") {
      shiny::validate(shiny::need(
        !all(is.na(.data[.gvar])),
        message = "The color variable appears to not have any data for this project. Please choose another option."
      ))
    }

    if (!is.null(.fvar) & !.fvar == "none") {
    shiny::validate(shiny::need(
      !all(is.na(.data[.fvar])),
      message = "The facet variable appears to not have any data for this project. Please choose another option."
    ))
    }

    if (is.null(.gvar) | .gvar == "none") {
      .gvar <- NULL
    } else {
      .gvar <- rlang::sym(.gvar)
    }

    if (is.null(.fvar) | .fvar == "none") {
      .fvar <- NULL
    } else {
      .fvar <- rlang::sym(.fvar)
    }


    breaks <- c((.cut_points[[1]] - 1),
                round(seq.int(.cut_points[[1]], .cut_points[[2]], length.out = diff(.cut_points)/3 + 1), 0),
                (.cut_points[[2]] + 1))

    labels <-
      c(paste0(.cut_points[[1]], "<"),
        round(seq.int(.cut_points[[1]], .cut_points[[2]], length.out = diff(.cut_points)/3 + 1), 0),
        paste0(">", .cut_points[[2]]))

    P <-
      .data %>%
      dplyr::mutate(trunc_indel_size = truncate_numeric(.data$IndelSize, .cut_points)) %>%
      ggplot2::ggplot() +
      ggplot2::aes(x = trunc_indel_size, y = Fq, color = !!.gvar) +
      ggplot2::geom_jitter(
        size = 3,
        alpha = 0.6,
        width = 0.3,
        height = 0
      ) +
      ggplot2::scale_x_continuous(breaks = breaks, labels = labels) +
      ggplot2::labs(title = .title, x = .xlab, y = .ylab) +
      ggplot2::facet_wrap(.fvar, ncol = 1) +
      ggplot2::theme_bw() +
      ggplot2::theme(axis.text.x = ggplot2::element_text(
        angle = 30,
        hjust = 1,
        vjust = 1
      ))

    plotly::ggplotly(P, width = .dims[[1]], height = .dims[[2]]) %>%
      plotly::config(displaylogo = FALSE) %>%
      plotly::layout(margin = c(
        t = 50,
        r = 50,
        l = 50,
        b = 50
      ))
  }
teofiln/gene.editing.dash documentation built on Feb. 21, 2022, 12:59 a.m.