生产刻面条形图的有效方法

时间:2017-07-04 22:02:32

标签: r ggplot2 tidyverse

有没有办法像生产刻面的箱形图一样快速生成刻面条形图?

例如,此代码将生成由分组变量构成的箱形图:

library(tidyverse)

mtcars %>% 
  ggplot(aes(x = am, y = mpg)) + 
  geom_boxplot() + 
  facet_grid(~ cyl)

但"相同"条形图的代码失败,因为geom_col()期望提供方法,这需要相当多的时间来计算:

mtcars %>% 
  ggplot(aes(x = am, y = mpg)) + 
  geom_col() + 
  facet_grid(~ cyl)

如果有办法以刻面盒子图的速度生成刻面条形图,我很乐意听你的方法。

2 个答案:

答案 0 :(得分:1)

这两个地块似乎没有显着差异

library(tidyverse)

box_plot <- function() mtcars %>% 
  ggplot(aes(x = am, y = mpg)) + 
  geom_boxplot() + 
  facet_grid(~ cyl)

bar_plot <- function() mtcars %>% 
  ggplot(aes(x = am, y = mpg)) + 
  geom_col() + 
  facet_grid(~ cyl)

library(microbenchmark)

mb <- microbenchmark(box_plot(), bar_plot())

mb
# Unit: milliseconds
#        expr      min       lq     mean   median       uq      max neval cld
#  box_plot() 2.412589 2.431660 2.538586 2.475522 2.534515 9.966422  1000   a 
#  bar_plot() 2.543288 2.566173 2.670544 2.609146 2.671571 5.254653  1000   b

autoplot(mb)

enter image description here

与完整钻石数据集的类似测试产生相同的结果。我认为瓶颈是需要大量时间来显示ggplot对象的图形设备。

box_p <- box_plot()
bar_p <- bar_plot()

# !!! this will need about 2 minutes to execute !!!
mb2 <- microbenchmark(plot(box_p), plot(bar_p), times = 100)

mb2
# Unit: milliseconds
#         expr      min       lq     mean   median       uq      max neval cld
#  plot(box_p) 405.0375 513.7360 532.1827 524.1259 536.8206 740.7494   100   b
#  plot(bar_p) 454.6047 469.3411 489.3676 479.3709 497.9246 717.7909   100  a 

autoplot(mb2)

enter image description here

答案 1 :(得分:0)

感谢@hrbrmstr建议您使用stat_summary()。那是完美的解决方案。

mtcars %>% 
  ggplot(aes(x = as.factor(am), y = mpg)) + 
  stat_summary(fun.y = "mean", geom = "col") + 
  facet_grid(~ cyl)

facetted bar plot