How can I extract plot axes' ranges for a ggplot2 object?
November 2018 UPDATE
As of ggplot2
version 3.1.0, the following works:
obj <- qplot(mtcars$disp, bins = 5)
# x range
ggplot_build(obj)$layout$panel_params[[1]]$x.range
# y range
ggplot_build(obj)$layout$panel_params[[1]]$y.range
A convenience function:
get_plot_limits <- function(plot) {
gb = ggplot_build(plot)
xmin = gb$layout$panel_params[[1]]$x.range[1]
xmax = gb$layout$panel_params[[1]]$x.range[2]
ymin = gb$layout$panel_params[[1]]$y.range[1]
ymax = gb$layout$panel_params[[1]]$y.range[2]
list(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax)
}
get_plot_limits(p)
Until the next update...
I am using ggplot2
version 2, I am not sure if this is same is previous version,
Suppose you have saved your plot on plt
object. It is easy to extract the ranges,
# y-range
layer_scales(plt)$y$range$range
# x-range
layer_scales(plt)$x$range$range
In case of facet plot, you can access scales of individual facets using layer_scales(plot, row_idx, col_idx)
. For example to access the facet at first row and second column,
# y-range
layer_scales(plt, 1, 2)$y$range$range
# x-range
layer_scales(plt, 1, 2)$x$range$range
In newer versions of ggplot2, you can find this information among the output of ggplot_build(p)
, where p
is your ggplot object.
For older versions of ggplot (< 0.8.9), the following solution works:
And until Hadley releases the new version, this might be helpful. If you do not set the limits in the plot, there will be no info in the ggplot object. However, in that case you case you can use the defaults of ggplot2 and get the xlim and ylim from the data.
> ggobj = ggplot(aes(x = speed, y = dist), data = cars) + geom_line()
> ggobj$coordinates$limits
$x
NULL
$y
NULL
Once you set the limits, they become available in the object:
> bla = ggobj + coord_cartesian(xlim = c(5,10))
> bla$coordinates$limits
$x
[1] 5 10
$y
NULL