0

I have a ggplot object returned by a function in an R package. I want to add some elements to this plot before plotting it. But, I do not know the plot limits. Is there a way to query the ggplot object to find the plot limits? Actually, what I'd really like to do is simply set new limits for subsequent plotting, but I understand this is not possible, based on discussions of the impossibility of plotting data against two different y-axes.

For example, say I want to plot a small rectangle in lower-left corner of plot, but not knowing the plot limits, I don't know where to put it:

p = function() return(ggplot() + xlim(-2, 5) + ylim(-3, 5) +
    geom_rect(mapping=aes(xmin=1, xmax=2, ymin=1, ymax=2)))
gp = p()
gp = gp + geom_rect(mapping=aes(xmin=0, ymin=0, xmax=0.5, ymax=0.5))
print(gp)
tedtoal
  • 913
  • 9
  • 20
  • Please add a reproducible example. Some ideas for how to do this shown [here](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – aosmith Oct 13 '16 at 23:22
  • "Is there a way to query the ggplot object to find the plot limits?" Sure np. Give me a reproducible example and I'll show you. – Hack-R Oct 13 '16 at 23:31

2 Answers2

1

In ggplot2 3.0.0:
ggplot_build(gp)$layout$panel_params[[1]][c("x.range","y.range")]

0
ggplot_build(p)$layout$panel_ranges[[1]][c("x.range","y.range")]
baptiste
  • 73,538
  • 17
  • 190
  • 281