R/plot_map.R

#' Plot graphene curve fit
#'
#' Accepts a dataframe with columns x, y and value to plot a raster map
#'
#' @param df Dataframe with columns x, y and value
#' @param name Name of the plot (goes on the colorbar)
#' @param scalebar Size of the scalebar (defaults to 1 um)
#' @param palette Color palette used in the map. Defaults to Spectral. See `RColorBrewer::display.brewer.all()` for more options
#' @keywords raman, curve fit, map
#' @family curve fit functions
#' @export
#' @examples
#' gr_cf_plot(df, "2D/G-ratio", scalebar = 5)

gr_cf_plot <- function(df, name, scalebar = 1, palette = "Spectral") {
  sb = tibble::tibble(x1 = max(df$x) - 0.1, x2 = x1 - scalebar, y1 = max(df$y) - 0.1, y2 = y1 - scalebar/8)
  scalebar = tibble::tribble(
    ~x, ~y,
    sb$x1, sb$y1,
    sb$x1, sb$y2,
    sb$x2, sb$y2,
    sb$x2, sb$y1
  )

  ggplot2::ggplot(data = df, ggplot2::aes(x = x, y = y, fill = value)) +
    ggplot2::geom_raster() +
    ggplot2::coord_equal() +
    ggplot2::theme(
      axis.text = ggplot2::element_blank(),
      axis.ticks = ggplot2::element_blank(),
      axis.title = ggplot2::element_blank()
    ) +
    ggplot2::scale_fill_distiller(name = name, palette = palette) +
    ggplot2::geom_polygon(data = scalebar, ggplot2::aes(x = x, y = y), fill = "white") +
    ggplot2::scale_y_reverse()
}


#' Plot all curve fit maps at once
#'
#' All curve fit maps in \code{df} are plotted in a grid.
#'
#' @param df A curve fit data frame, as generated by \code{gr_cf_read}
#' @param ncol Number of columns in the generated grid.
#' @inheritParams gr_cf_plot
#' @importFrom magrittr %>%
#' @family curve fit functions
#' @export
#'

gr_cf_plot_all <- function(df, scalebar = 1, palette = "Spectral", ncol = 3) {
  df %>%
    gr_cf_nest() %>%
    dplyr::mutate(plots = purrr::map2(data, param, gr_cf_plot, scalebar = scalebar, palette = palette)) %>%
    gridExtra::grid.arrange(grobs = .$plots, ncol = ncol, bottom = stringr::str_c("Scalebar = ", scalebar, " um"))
}

#' Return a nested tibble contaning all curve fits
#'
#' This is mostly an internal function. The nested tibble is used by \code{gr_cf_plot_all()}.
#'
#' @param df A dataframe from \code{gr_cf_read}
#'
#' @importFrom magrittr %>%
#' @export
#'

gr_cf_nest <- function(df) {
  df %>%
    tidyr::gather(key = "param", value = "value", -id, -x, -y, convert = TRUE) %>%
    dplyr::group_by(param) %>%
    tidyr::nest()
}
emilbp/gRaphene documentation built on May 16, 2019, 5:07 a.m.