]> git.donarmstrong.com Git - r/CairoHacks.git/blob - R/raster_plots.R
use grid:: and Cairo::
[r/CairoHacks.git] / R / raster_plots.R
1 ##' Start a raster plot with indicated width or height in pixels
2 ##'
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.
9 ##' @return NULL
10 ##' @author Don Armstrong
11 ##' @export
12 ##' @import Cairo grid
13 ##' @examples
14 ##' \dontrun{
15 ##' ### plot a raster plot in a PDF
16 ##' pdf()
17 ##' start_rasterplot()
18 ##' print(xyplot(y~x,
19 ##'      data=data.frame(y=rnorm(1E8),x=rnorm(1E8))))
20 ##' stop_rasterplot()
21 ##' dev.off()
22 ##' }
23 ##'
24 ##' ### plot a raster plot using grid.raster
25 ##' start_rasterplot(width=100)
26 ##' print(plot(y~x,
27 ##'             data=data.frame(y=rnorm(1E4),
28 ##'                             x=rnorm(1E4))))
29 ##' raster.image <- stop_rasterplot(plot=FALSE)
30 ##' grid::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)) {
37         width <- 1024
38     }
39     if (is.null(width)) {
40         width <- height*x.y.ratio
41     }
42     else if (is.null(height)) {
43         height <- width/x.y.ratio
44     } else {
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."))
50         }
51     }
52         
53     Cairo::Cairo(width=width,height=height,dpi=width/width.points*dpi,file="/dev/null")
54     NULL
55 }
56 ##' Stops a raster plot and returns the results and optionally plots them
57 ##'
58 ##' This stops a raster plot created with start_rasterplot and plots
59 ##' the result.
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
65 ##' @export
66 ##' @seealso start_rasterplot
67 stop_rasterplot <- function(plot=TRUE) {
68     raster.image <- grDevices::dev.capture(native=TRUE)
69     grDevices::dev.off()
70     if (plot) {
71         grid::grid.raster(raster.image,width=grid::unit(1,"npc"),height=grid::unit(1,"npc"))
72     }
73     invisible(raster.image)
74 }