2

Me encuentro graficando un histograma a partir de un conjunto muy importante de datos mediante geom_histogram(), me he dado cuenta que a medida que se aumenta la "definición" del mismo aumentando en numero de bins o barras, el resultado es cada vez es más lento. La relación, con un histograma de R base es de al menos 10 a 1 en tiempo. Ejemplo:

library("ggplot2")
library("microbenchmark")
set.seed(2019)
x <- rnorm(100000)
df <- data.frame(x=x)

ggplot_hist <- function(data, bins=100000){
  print(ggplot(data, aes(x=x)) + geom_histogram(bins=bins))
}

base_hist <- function(x, breaks=100000){
  print(hist(x, breaks=length(x)))
}

microbenchmark(
  base_hist(x), 
  ggplot_hist(df), 
  times=3L 
)

Unit: seconds
            expr       min        lq      mean    median        uq       max neval
    base_hist(x)  4.503556  4.632358  4.680143  4.761159  4.768436 4.775713     3
 ggplot_hist(df) 56.330033 57.249490 60.182923 58.168946 62.109369 66.049791    3

¿Hay forma de optimizar un histograma en ggplot?

1 respuesta 1

2

Según la hipótesis de esta interesante respuesta, el cuello de botella estaría en el calculo de los bins o barras. Podemos intentar probarlo:

microbenchmark(
  ggplot_hist(df, bins=1), 
  ggplot_hist(df, bins=100), 
  ggplot_hist(df, bins=1000), 
  ggplot_hist(df, bins=10000), 
  ggplot_hist(df, bins=100000), 
  times=3
) -> tiempos
summary(tiempos)[, c(1,4), drop=FALSE]

                           expr       mean
1     ggplot_hist(df, bins = 1)   502.0619
2   ggplot_hist(df, bins = 100)   705.1292
3  ggplot_hist(df, bins = 1000)  1209.0673
4 ggplot_hist(df, bins = 10000)  6143.7755
5 ggplot_hist(df, bins = 1e+05) 55068.0312

Podemos observar, que a medida que incorporamos más nivel de detalle aumentando los bins el tiempo crece rápidamente. Por otro lado, si estudiamos el histograma "base" así:

microbenchmark(
  base_hist(df$x, breaks=1), 
  base_hist(df$x, breaks=100), 
  base_hist(df$x, breaks=1000), 
  base_hist(df$x, breaks=10000), 
  base_hist(df$x, breaks=100000), 
  times=3
) -> tiempos_base

summary(tiempos_base)[, c(1,4), drop=FALSE]
                             expr     mean
1     base_hist(df$x, breaks = 1) 10.49051
2   base_hist(df$x, breaks = 100) 10.46801
3  base_hist(df$x, breaks = 1000) 13.60592
4 base_hist(df$x, breaks = 10000) 16.48910
5 base_hist(df$x, breaks = 1e+05) 13.49401

Con el histograma básico, vemos que el crecimiento en el tiempo a medida que aumentan los bins es mínimo. Por lo que la idea, que se propone en la respuesta mencionada, es reemplazar el calculo de los bins con la función base hist() y dibujar luego las barras mediante un geom_rect(). Veamos:

quick_hist = function(x, bins=100000) {

  res = hist(x, plot=FALSE, breaks=bins)
  dat = data.frame(xmin=head(res$breaks, -1L),
                   xmax=tail(res$breaks, -1L),
                   ymin=0.0,
                   ymax=res$counts)

  print(ggplot(dat, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax)) +
    geom_rect(size=0.5))
}

print(microbenchmark(
  base_hist(x), 
  ggplot_hist(df), 
  quick_hist(df$x), 
  times=3L 
), signif=3)

Unit: seconds
             expr   min    lq  mean median    uq  max neval
     base_hist(x)  4.75  4.76  7.70   4.76  9.17 13.6     3
  ggplot_hist(df) 57.30 57.40 57.60  57.40 57.80 58.1     3
 quick_hist(df$x)  6.45  6.64  9.57   6.83 11.10 15.4     3

Y vemos que con la función ad-hoc quick_hist()hemos logrado usando ggplot mejorar la performance del histograma de una forma radical y con un resultado visual muy similar.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.