I have an R/ggplot2 use case that seems to call for geom_raster: a regular Cartesian grid with z-values at x, y locations. I’ve been using geom_tile, and I expected a performance improvement from switching to geom_raster. But I don’t seem to be seeing one…
Here’s a toy example (but about the right size), using base graphics:
n <- m <- 200
x <- 1:n
y <- 1:m
f <- function(x, y) 10 * sin(x / n) * cos(y / m)
z <- outer(x, y, f)
system.time(image(z))
user system elapsed
0.998 0.007 1.023
Here it is with ggplot2:
obs <- expand.grid(x=x, y=y)
obs$z <- as.numeric(as.list(z))
require(ggplot2)
p <- ggplot(obs, aes(x=x, y=y, fill=z))
system.time(show(p + geom_tile()))
user system elapsed
7.328 0.891 8.187
require(ggExtra)
system.time(show(p + geom_raster()))
user system elapsed
7.000 0.637 7.799
So, a modest gain, but nowhere near what I was expecting. Am I doing it wrong? Many thanks in advance!
You should use
geom_rasterfrom the latestggplot2(dev version, currently), not the buggy prototype inggExtra(this package is now deprecated, btw).Doing so, I get better results, 4.705 vs. 1.416 (elapsed). Quite an improvement.
Edit: it turns out that
?geom_rasteringgplot2already offers a better benchmark, on my system