0

I´m having some troubles trying to extract into a table the five number values of a geom_boxplot. I know it works easily with boxplot$stats, however, I cannot find the way to extract the same information from a boxplot made in ggplot2. Can anyone help me?

this is the code of the graph:

graf332 <- bd %>%
 filter(!(DIAGNOST %in% c("Otras Enf eosinofilicas del TGI", "Esofagitis Eosinofilica"
))) %>%
 ggplot(aes(x = DIAGNOST, y = EDAD, fill = SEXO)) +
 geom_boxplot() +
 scale_fill_hue() +
 labs(x = "Diagnóstico", y = "Edad en meses", 
      title = "Distribución de la población por diagnóstico según edad en meses y discriminado por sexo",
      fill = "Sexo") +
 theme_minimal()

and this is the graph: enter image description here

Phil
  • 7,287
  • 3
  • 36
  • 66
Paul Gis
  • 1
  • 1

1 Answers1

3

For any layer in ggplot2, you can extract the underlying data with layer_data(). For boxplots, the whisker endpoints are ymin and ymax, the box endspoints are lower and upper, whereas the median is middle. This is documented in the 'computed variables' section of ?stat_boxplot.

library(ggplot2)

g <- ggplot(mpg, aes(class, displ)) +
  geom_boxplot()

layer_data(g)
#>   ymin lower middle upper ymax outliers notchupper notchlower x flipped_aes
#> 1  5.7   5.7   6.20  6.20  6.2        7   6.553299   5.846701 1       FALSE
#> 2  1.8   2.0   2.20  2.80  3.3            2.384373   2.015627 2       FALSE
#> 3  1.8   2.4   2.80  3.50  4.2      5.3   3.071430   2.528570 3       FALSE
#> 4  3.0   3.3   3.30  3.80  4.0      2.4   3.538194   3.061806 4       FALSE
#> 5  2.7   3.9   4.70  4.70  5.9            4.920034   4.479966 5       FALSE
#> 6  1.6   1.9   2.20  3.25  4.6      5.4   2.560543   1.839457 6       FALSE
#> 7  2.5   4.0   4.65  5.30  6.5            4.910858   4.389142 7       FALSE
#>   PANEL group ymin_final ymax_final  xmin  xmax xid newx new_width weight
#> 1     1     1        5.7        7.0 0.625 1.375   1    1      0.75      1
#> 2     1     2        1.8        3.3 1.625 2.375   2    2      0.75      1
#> 3     1     3        1.8        5.3 2.625 3.375   3    3      0.75      1
#> 4     1     4        2.4        4.0 3.625 4.375   4    4      0.75      1
#> 5     1     5        2.7        5.9 4.625 5.375   5    5      0.75      1
#> 6     1     6        1.6        5.4 5.625 6.375   6    6      0.75      1
#> 7     1     7        2.5        6.5 6.625 7.375   7    7      0.75      1
#>   colour  fill size alpha shape linetype
#> 1 grey20 white  0.5    NA    19    solid
#> 2 grey20 white  0.5    NA    19    solid
#> 3 grey20 white  0.5    NA    19    solid
#> 4 grey20 white  0.5    NA    19    solid
#> 5 grey20 white  0.5    NA    19    solid
#> 6 grey20 white  0.5    NA    19    solid
#> 7 grey20 white  0.5    NA    19    solid

Created on 2021-04-17 by the reprex package (v1.0.0)

teunbrand
  • 33,645
  • 4
  • 37
  • 63