##' Start a raster plot with indicated width or height in pixels ##' ##' This creates a Cairo device with output to /dev/null of width or ##' height given (defaulting to a width of 1024) ##' @title start_rasterplot ##' @param width Width in pixels of raster image ##' @param height Height in pixels of raster image. In general only ##' one of \code{width} or \code{height} should be provided. ##' @return NULL ##' @author Don Armstrong ##' @export ##' @import Cairo grid ##' @examples ##' \dontrun{ ##' ### plot a raster plot in a PDF ##' pdf() ##' start_rasterplot() ##' print(xyplot(y~x, ##' data=data.frame(y=rnorm(1E8),x=rnorm(1E8)))) ##' stop_rasterplot() ##' dev.off() ##' } ##' ##' ### plot a raster plot using grid.raster ##' start_rasterplot(width=100) ##' print(plot(y~x, ##' data=data.frame(y=rnorm(1E4), ##' x=rnorm(1E4)))) ##' raster.image <- stop_rasterplot(plot=FALSE) ##' grid.raster(raster.image) start_rasterplot <- function(width=NULL,height=NULL) { x.y.ratio <- grid::convertX(grid::unit(1,"npc"),"mm",valueOnly=TRUE)/ grid::convertY(grid::unit(1,"npc"),"mm",valueOnly=TRUE) width.points <- as.numeric(grid::convertX(grid::unit(1,"npc"),"points")) dpi <- as.numeric(grid::convertX(grid::unit(1,"inch"),"point")) if (is.null(width) && is.null(height)) { width <- 1024 } if (is.null(width)) { width <- height*x.y.ratio } else if (is.null(height)) { height <- width/x.y.ratio } else { if (height != width/x.y.ratio) { warning(paste0("You've provided both width and height, ", "but they do not match the actual ratio ", "of the plot. Consider only providing one ", "if the results look bad.")) } } Cairo::Cairo(width=width,height=height,dpi=width/width.points*dpi,file="/dev/null") NULL } ##' Stops a raster plot and returns the results and optionally plots them ##' ##' This stops a raster plot created with start_rasterplot and plots ##' the result. ##' @title stop_rasterplot ##' @param plot Boolean indicating whether the captured raster image ##' should be plotted or not ##' @return raster image suitable for plotting with \code{grid.raster()} ##' @author Don Armstrong ##' @export ##' @seealso start_rasterplot stop_rasterplot <- function(plot=TRUE) { raster.image <- dev.capture(native=TRUE) dev.off() if (plot) { grid::grid.raster(raster.image,width=grid::unit(1,"npc"),height=grid::unit(1,"npc")) } invisible(raster.image) }