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_raster
from the latest ggplot2
(dev version, currently), not the buggy prototype in ggExtra
(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_raster
in ggplot2
already offers a better benchmark, on my system
benchplot(base + geom_raster())
step user.self sys.self elapsed
1 construct 0.006 0.004 0.010
2 build 0.887 0.212 1.109
3 render 0.449 0.119 0.584
4 draw 0.108 0.005 0.141
5 TOTAL 1.450 0.340 1.844
> benchplot(base + geom_tile())
step user.self sys.self elapsed
1 construct 0.016 0.005 0.026
2 build 1.031 0.329 1.365
3 render 1.021 0.297 1.318
4 draw 0.987 0.041 1.040
5 TOTAL 3.055 0.672 3.749
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With