Skip to content
Snippets Groups Projects
draw.R 1.61 KiB
Newer Older
Gilquin's avatar
Gilquin committed
####
# Plotting functions.
####

# global imports
import::here("dplyr", "filter", .character_only = TRUE)
import::here(
  "ggplot2",
  c(
    "aes", "facet_wrap", "geom_histogram", "geom_raster", "ggplot",
    "scale_x_continuous", "scale_y_continuous", "scale_fill_viridis_c"
  ),
  .character_only = TRUE
)
import::here("magrittr", "%>%", .character_only = TRUE)

# local import
import::here("image.R", "img_to_df", .character_only = TRUE)


#' Channel histogram
#'
#' Histogram ggplot of each color channel of an image.
#'
#' @param img an imager::cimg
Gilquin's avatar
Gilquin committed
#' @param ch a character vector, subset of ("R", "G", "B").
Gilquin's avatar
Gilquin committed
#'
#' @returns a ggplot2 graph
Gilquin's avatar
Gilquin committed
channel_hist <- function(img, ch = c("R", "G", "B")) {
  if (all(ch %in% c("R", "G", "B"))) {
Gilquin's avatar
Gilquin committed
    gg <- img %>%
      img_to_df() %>%
Gilquin's avatar
Gilquin committed
      filter(channel %in% ch) %>%
Gilquin's avatar
Gilquin committed
      ggplot(aes(value, col = channel)) +
      geom_histogram(bins = 30L) +
      facet_wrap(~channel)
  } else {
    stop("Invalid 'cc' argument.")
  }
  return(gg)
}


#' Raster channel
#'
#' Raster ggplot of an image channel.
#'
#' @param img an imager::cimg
Gilquin's avatar
Gilquin committed
#' @param ch character, specify the image channel, one of "R", "G", "B".
Gilquin's avatar
Gilquin committed
#'
#' @returns a ggplot2 graph
Gilquin's avatar
Gilquin committed
raster_channel <- function(img, ch = NULL) {
  if (ch %in% c("R", "G", "B")) {
Gilquin's avatar
Gilquin committed
    gg <- img %>%
      img_to_df() %>%
Gilquin's avatar
Gilquin committed
      filter(channel == ch) %>%
Gilquin's avatar
Gilquin committed
      ggplot(aes(x, y, fill = value)) +
      geom_raster() +
      scale_x_continuous(expand = c(0L, 0L)) +
      scale_y_continuous(expand = c(0L, 0L), trans = scales::reverse_trans()) +
      scale_fill_viridis_c(direction = 1L, option = "plasma")
  } else {
    stop("Invalid 'cc' argument.")
  }

  return(gg)
}