Iterator Iterator - 9 months ago 90
R Question

How can I extract plot axes' ranges for a ggplot2 object?

I have an object from

, say
, how can I identify the ranges for the x and y axes?

It doesn't seem to be a simple multiple of the data values' range, because one can rescale plots, modify axes' ranges, and so on.
) and Google don't seem to be turning up relevant results, other than how to set the axes' ranges.

Answer Source

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



Once you set the limits, they become available in the object:

> bla = ggobj + coord_cartesian(xlim = c(5,10))
> bla$coordinates$limits
[1]  5 10