NOAA-EDAB / ecodata

A data package for reporting on Northeast Continental Shelf ecosystem status and trends.
https://noaa-edab.github.io/ecodata/
Other
31 stars 12 forks source link

add watermark to figures #55

Open sgaichas opened 1 year ago

sgaichas commented 1 year ago

add a theme, e.g. theme_watermark() that optionally adds an image credit to plots

adamkemberling commented 4 weeks ago

I've had okay luck with this approach. It does the job, but it can be finicky depending on the logo and plot sizes. Just need to put the watermark images in the ecodata package so the function can find them. The default option finds ours this way: paste0(system.file("stylesheets", package = "gmRi"), "/gmri_logo.png").

Also need to run + coord_cartesian(clip = "off") for logos to be visible outside of the main plot panel. This last step will cause undesirable behavior when used with coord_sf for maps, as map elements that were outside the bounds of coord_sf will then also be visible.

Its an okay solution though.

#' @title Ggplot2 Raster Logo as Geom Layer
#'
#' @param logo Any R object that can be coerced to a raster object. Ex. class of "magick-image"
#' @param x_npc x positioning for logo in normalized parent coordinates 0-1 left to right
#' @param y_npc y positioning for logo in normalized parent coordinates 0-1 bottom to top
#' @param logo_height Desired height of the logo
#' @param height_units Units to set the height (and width) for the logo.
#' Default is NPC i.e. a fraction of the plot panel height
#' @param ... Extra control options passed to ggplot2::annotation_custom()
#'
#' @return Returns a  ggplot geom layer
#' @export
#'
#' @examples
#' library(ggplot2)
#' ggplot(mtcars, aes(cyl, hp)) + geom_point() + geom_logo(logo_height = 0.06)
geom_logo <- function(logo = NULL, x_npc = 0.9, y_npc = 0.925, logo_height = 0.06, height_units = "npc", ...){

  # Default logo is gmri_logo saved within the package
  if(is.null(logo)){
    logo_path <- paste0(system.file("stylesheets", package = "gmRi"), "/gmri_logo.png")
    logo <- magick::image_read(logo_path)
  }

  # Get image dimensions - to preserve aspect ratio:
  w <- magick::image_info(logo)$width
  h <- magick::image_info(logo)$height

  # Get the desired output height in npc units
  # npc = normalized parent coordinates
  npc_height <- logo_height
  npc_width  <- (npc_height * w) / h

  # Make the grob
  g <- grid::grobTree(
    grid::rasterGrob(image = logo,
                     x = grid::unit(x_npc, "npc"),
                     y = grid::unit(y_npc, "npc"),
                     height = grid::unit(npc_height, height_units),
                     width = grid::unit(npc_width, height_units)))

  # Make annotation geom
  geom_logo <- ggplot2::annotation_custom(g, ...)

  # Return the geom
  return(geom_logo)

}
sgaichas commented 1 week ago

A contributor credit can also be added to the watermark