[R] need for speed on grid.rect

Mikkel Grum mi2kelgrum at yahoo.com
Wed Oct 20 19:10:36 CEST 2010


When I use grid.rect to print a multi-coloured grid, it is incredibly slow compared to a single colour grid, or even a two colour grid.

I've set out some simplified examples below. This is something I run literally thousands of times a day, so I would greatly appreciate any hints on how I might improve the speed???

library(grid)
pushViewport(viewport(
    width = unit(100, "native"),
    height = unit(100, "native"),
    xscale = c(0, 100),
    yscale = c(0, 100),
    ))
pushViewport(viewport(
    x = unit(10, "native"),
    y = unit(10, "native"),
    width = unit(100, "native"),
    height = unit(200, "native"),
    xscale = c(0, 100),
    yscale = c(0, 200),
    just = c("left", "bottom"),
    angle = 10))
system.time(grid.rect(x = unit(rep(1:100, 200) , "native"),
    y = unit(rep(1:200, each = 100), "native"),
    width = unit(1, "native"),
    height = unit(1, "native"),
    gp = gpar(col = NA,
		fill = "lightblue")
))
system.time(grid.rect(x = unit(rep(1:100, 200) , "native"),
    y = unit(rep(1:200, each = 100), "native"),
    width = unit(1, "native"),
    height = unit(1, "native"),
    gp = gpar(col = NA,
		fill = rgb(1, 0, 0, 1:20000/40000))
))

My times for the two plots are:
   user  system elapsed 
   0.61    0.30    0.92 
vs
  user  system elapsed 
   0.08    0.36   24.39 

The time it takes to calculate the colours clearly doesn't explain the difference:
system.time(rgb(1, 0, 0, 1:20000/20000))
   user  system elapsed 
      0       0       0 

Even if I do a two coloured grid, it finishes as quickly as the single coloured one, so my first interpretation is that the function finds the colours fairly quickly, e.g.

system.time(grid.rect(x = unit(rep(1:100, 200) , "native"),
    y = unit(rep(1:200, each = 100), "native"),
    width = unit(1, "native"),
    height = unit(1, "native"),
    gp = gpar(col = NA,
		fill = c("lightblue", "red"))
))

   user  system elapsed 
   0.51    0.18    0.70

Best regards,
Mikkel
> sessionInfo()
R version 2.12.0 (2010-10-15)
Platform: i386-pc-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=English_Ireland.1252  LC_CTYPE=English_Ireland.1252   
[3] LC_MONETARY=English_Ireland.1252 LC_NUMERIC=C                    
[5] LC_TIME=English_Ireland.1252    

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods  
[8] base     

loaded via a namespace (and not attached):
[1] tools_2.12.0



More information about the R-help mailing list