Last active
October 2, 2020 10:36
-
-
Save tomhopper/9076152 to your computer and use it in GitHub Desktop.
Get the actual x- and y-axis ranges from a ggplot object. Works on ggplot2 >= 0.8.9 (tested on 0.9.3.1). Code from http://stackoverflow.com/questions/7705345/how-can-i-extract-plot-axes-ranges-for-a-ggplot2-object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggplot2) | |
#' create a data frame with test data. | |
my.df <- data.frame(index = 1:10, value = rnorm(10)) | |
#' create the ggplot object | |
my.ggp <- ggplot(data = my.df, aes(x = index, y = value)) + geom_point() + geom_line() | |
#' get the x- and y-axis ranges actually used in the graph | |
# This worked in early versions of ggplot2 (probably <2.2) | |
# my.ggp.yrange <- ggplot_build(my.ggp)$panel$ranges[[1]]$y.range | |
# my.ggp.xrange <- ggplot_build(my.ggp)$panel$ranges[[1]]$x.range | |
# As of ggplot2 3.x: | |
ggplot_build(my.ggp)$layout$panel_scales_x[[1]]$range$range | |
ggplot_build(my.ggp)$layout$panel_scales_y[[1]]$range$range | |
# Without having tested, assume the extraction operator | |
# applies to graphs with more than one panel (facet?) |
Not working anymore
Now you can use:
library(ggplot2)
#' create a data frame with test data.
my.df <- data.frame(index = 1:10, value = rnorm(10))
#' create the ggplot object
my.ggp <- ggplot(data = my.df, aes(x = index, y = value)) + geom_point() + geom_line()
#' get the x- and y-axis ranges actually used in the graph
my.ggp.yrange <- ggplot_build(my.ggp)$layout$panel_ranges[[1]]$y.range
my.ggp.xrange <- ggplot_build(my.ggp)$layout$panel_ranges[[1]]$x.range
Thank you Rekyt. I assume this broke with the last ggplot2 upgrade.
Thanks @Rekyt, I'd +1 if I could
I now have 2.2.2.1 and it doesn't work. Any suggestions?
As of ggplot2 v. 2.2.1, there's
ggp <- ggplot_build(p1)
my.ggp.yrange <- ggp$layout$panel_scales_y[[1]]$range$range # data range!
my.ggp.xrange <- ggp$layout$panel_scales_x[[1]]$range$range # data range!
The returned values are atomic, numeric vectors. I assume the [[1]]
index is for multiple panels (facets).
UPDATE: I noticed the above are for the untrained, unextended ranges.
From the link at the top, we have:
ggp$layout$panel_params[[1]]$x.range
ggp$layout$panel_params[[1]]$y.range
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was very helpful.