2

有没有办法提高ggplot使用 的图形的生产速度facet_grid

facet_grid似乎让事情慢了很多。当向情节添加额外的功能时,情况会变得更糟facet_grid

例子:

创建虚拟数据:

library(ggplot2)
library(rbenchmark)

df <- data.frame(cbind(rate=runif(60,0,1),period=(rep(c(1:6),10)),colour=sample(c("firebrick3","seagreen3","cadetblue"),60,replace=TRUE)
,gridvar=rep(paste0("class",1:10),each=6)))

df$rate <- as.numeric(as.character(df$rate))
df$upper <- df$rate +1
df$lower <-  df$rate -1

使用 facet_grid:

benchmark(replications=10,
 path={print(ggplot(df) + geom_path(aes(y=rate,x=period,group=1),size=1)  + facet_grid( gridvar ~ .))},

pathError={print(ggplot(df) + geom_path(aes(y=rate,x=period,group=1),size=1) + geom_errorbar( aes(ymax =upper, ymin=lower,x=period), width=0.25)  + facet_grid( gridvar ~ .))},

           pathErrorPoint={print(ggplot(df) + geom_path(aes(y=rate,x=period,group=1),size=1) + geom_errorbar( aes(ymax =upper, ymin=lower,x=period), width=0.25) + geom_point(aes(y=rate,x=period,colour=colour),size=5) + facet_grid( gridvar ~ .))}
)


#            test replications elapsed relative user.self sys.self user.child sys.child
#1           path           10   13.38    1.000     13.23     0.14         NA        NA
#2      pathError           10   22.01    1.040     21.70     0.16         NA        NA
#3 pathErrorPoint           10   38.43    2.874     37.60     0.27     NA        NA

没有 facet_grid:

 benchmark(replications=10,
           path={print(ggplot(df) + geom_path(aes(y=rate,x=period,group=1),size=1)  )},

           pathError={print(ggplot(df) + geom_path(aes(y=rate,x=period,group=1),size=1) + geom_errorbar( aes(ymax =upper, ymin=lower,x=period), width=0.25)  )},

           pathErrorPoint={print(ggplot(df) + geom_path(aes(y=rate,x=period,group=1),size=1) + geom_errorbar( aes(ymax =upper, ymin=lower,x=period), width=0.25) + geom_point(aes(y=rate,x=period,colour=colour),size=5) )}
 )


#            test replications elapsed relative user.self sys.self user.child sys.child
#1           path           10    2.99    1.000      2.85     0.03         NA        NA
#2      pathError           10    4.62    1.545      4.56     0.06         NA        NA
#3 pathErrorPoint           10    6.18    2.067      6.02     0.12         NA        NA

facet_grid每增加一个功能,情节的制作时间平均要多花 1-2 秒,从 1 秒到近 4 秒。没有facet_grid我们也看到增加,但具有最多特征的情节仍然需要不到 1 秒的时间来生成。需要更长的时间是正常的facet_grid,但是在小型数据集上绘制这样的图需要 3-4 秒,这比我预期的要多。有什么建议么?

4

0 回答 0