Home > Software design >  How can I check/extract the range of any scale in ggplot (size, color, etc)
How can I check/extract the range of any scale in ggplot (size, color, etc)

Time:10-17

If I want to check what the range for the size scale is set to for the plot below, how can I do that in ggplot?

plt <- ggplot(mpg, aes(displ, hwy, size = hwy))  
    geom_point()  
    scale_size(range = c(0, 5))
plt

For x and y I can use layer_scales(plt)$x$range$range from How can I extract plot axes' ranges for a ggplot2 object?, but for some reason using the same approach does not work with e.g. size and color. I have also tried plt$scales$get_scales('size') which cryptically returns another range for the scale that what is actually used in the plot:

<ScaleContinuous>
 Range:  
 Limits:    0 --    1

CodePudding user response:

Scales need to be trained before their range is calculated, so you cannot extract the ranges from the plot object unless you specifically train the scale with the data used to create the plot, or get ggplot to do this for you using ggplot_build:

range(ggplot_build(plt)$data[[1]]$size)
#> [1] 0 5
  • Related