Skip to content

Instantly share code, notes, and snippets.

@tomhopper
Last active October 2, 2020 10:36
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tomhopper/9076152 to your computer and use it in GitHub Desktop.
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
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?)
@davidlevybooth
Copy link

This was very helpful.

@umutcaglar
Copy link

Not working anymore

@Rekyt
Copy link

Rekyt commented Mar 27, 2017

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

@nguinasso
Copy link

Thank you Rekyt. I assume this broke with the last ggplot2 upgrade.

@jeffreyhanson
Copy link

Thanks @Rekyt, I'd +1 if I could

@nguinasso
Copy link

I now have 2.2.2.1 and it doesn't work. Any suggestions?

@stefanedwards
Copy link

stefanedwards commented Jun 20, 2018

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