geom_raster()的相对性能表现

6
我有一个与R/ggplot2相关的使用案例,似乎需要使用geom_raster:在x、y位置具有z值的常规笛卡尔网格。我一直在使用geom_tile,并且从切换到geom_raster中期望获得性能提升。但是我好像没有看到这个性能提升...
这里有一个玩具示例(但大约是正确的大小),使用base图形:
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 

这是使用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

所以,收益不算太多,但远远达不到我的预期。我是做错了吗?非常感谢您的帮助!

1个回答

9
你应该使用最新版的ggplot2(目前是dev版本),而不是ggExtra中存在缺陷的原型(顺便说一下,这个包现在已经被弃用了)。这样做可以获得更好的结果,4.705 vs. 1.416(经过的时间)。有很大的提高。编辑:事实证明,在我的系统上,ggplot2中的?geom_raster已经提供了更好的基准。
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接