1 ##' Start a raster plot with indicated width or height in pixels
3 ##' This creates a Cairo device with output to /dev/null of width or
4 ##' height given (defaulting to a width of 1024)
5 ##' @title start_rasterplot
6 ##' @param width Width in pixels of raster image
7 ##' @param height Height in pixels of raster image. In general only
8 ##' one of \code{width} or \code{height} should be provided.
10 ##' @author Don Armstrong
12 ##' @import Cairo grid
15 ##' ### plot a raster plot in a PDF
17 ##' start_rasterplot()
19 ##' data=data.frame(y=rnorm(1E8),x=rnorm(1E8))))
24 ##' ### plot a raster plot using grid.raster
25 ##' start_rasterplot(width=100)
27 ##' data=data.frame(y=rnorm(1E4),
29 ##' raster.image <- stop_rasterplot(plot=FALSE)
30 ##' grid.raster(raster.image)
31 start_rasterplot <- function(width=NULL,height=NULL) {
32 x.y.ratio <- grid::convertX(grid::unit(1,"npc"),"mm",valueOnly=TRUE)/
33 grid::convertY(grid::unit(1,"npc"),"mm",valueOnly=TRUE)
34 width.points <- as.numeric(grid::convertX(grid::unit(1,"npc"),"points"))
35 dpi <- as.numeric(grid::convertX(grid::unit(1,"inch"),"point"))
36 if (is.null(width) && is.null(height)) {
40 width <- height*x.y.ratio
42 else if (is.null(height)) {
43 height <- width/x.y.ratio
45 if (height != width/x.y.ratio) {
46 warning(paste0("You've provided both width and height, ",
47 "but they do not match the actual ratio ",
48 "of the plot. Consider only providing one ",
49 "if the results look bad."))
53 Cairo::Cairo(width=width,height=height,dpi=width/width.points*dpi,file="/dev/null")
56 ##' Stops a raster plot and returns the results and optionally plots them
58 ##' This stops a raster plot created with start_rasterplot and plots
60 ##' @title stop_rasterplot
61 ##' @param plot Boolean indicating whether the captured raster image
62 ##' should be plotted or not
63 ##' @return raster image suitable for plotting with \code{grid.raster()}
64 ##' @author Don Armstrong
66 ##' @seealso start_rasterplot
67 stop_rasterplot <- function(plot=TRUE) {
68 raster.image <- grDevices::dev.capture(native=TRUE)
71 grid::grid.raster(raster.image,width=grid::unit(1,"npc"),height=grid::unit(1,"npc"))
73 invisible(raster.image)