]> git.donarmstrong.com Git - don.git/blob - posts/embedded_raster_in_vector_plot.mdwn
add raster in vector plot post
[don.git] / posts / embedded_raster_in_vector_plot.mdwn
1 [[!meta title="Plotting Embedded Bitmap in Vector Plot in R"]]
2
3 Recently, one of my collaborators complained that one of my plots took
4 forever to render on his machine. The particular plot in question had
5 a few thousand points, many of which were overlapping. Ideally, R
6 would be able to simplify the vector image which was drawn to avoid
7 drawing points which were occluded by other points, but this is
8 difficult to do properly, and R currently doesn't do it.
9
10 However, R is able to plot to a bitmap, and bitmap images have the
11 nice property of automatically handling this for you. Furthermore,
12 raster images have recently been made far less clunky in R, so it's
13 pretty easy to shove an arbitrary bitmap image anywhere. With
14 `dev.capture` in Cairo coupled with `grid.raster` in grid, we have
15 everything we need to solve this problem:
16
17 [[!format R """
18 require(grid)
19 require(Cairo)
20
21 start.rasterplot <- function(width=NULL,height=NULL) {
22     x.y.ratio <- convertX(unit(1,"npc"),"mm",valueOnly=TRUE)/
23         convertY(unit(1,"npc"),"mm",valueOnly=TRUE)
24     width.points <- as.numeric(convertX(unit(1,"npc"),"points"))
25     dpi <- as.numeric(convertX(unit(1,"inch"),"point"))
26     if (is.null(width) && is.null(height)) {
27         width <- 1024
28     }
29     if (is.null(width)) {
30         width <- height*x.y.ratio
31     }
32     if (is.null(height)) {
33         height <- width/x.y.ratio
34     }
35     Cairo(width=width,height=height,dpi=1024/width.points*dpi,file="/dev/null")
36 }
37
38 stop.rasterplot <- function(plot=TRUE) {
39     raster.image <- dev.capture(native=TRUE)
40     dev.off()
41     if (plot) {
42         grid.raster(raster.image,width=unit(1,"npc"),height=unit(1,"npc"))
43         return(invisible())
44     } else {
45         return(raster.image)
46     }
47 }
48 """]]
49
50 Now we can do the following:
51
52 [[!format R """
53 pdf(file="raster.pdf")
54 start.rasterplot()
55 print(xyplot(y~x,
56       data=data.frame(y=rnorm(1E8),x=rnorm(1E8))))
57 stop.rasterplot()
58 dev.off()
59 """]]
60
61 and our PDF will contain a raster image, and will load in seconds
62 instead of taking forever to plot the file.
63
64 [[!tag r genetics biology]]