Retrieving axis scales from ggplot

Is there a way, hopefully not too complicated, to retrieve the axes from a ggplot? For example, from z in the following code?

t <- tibble(x=rnorm(10), y1 = x + rnorm(10), y2 = 2*x+rnorm(10))

z <-  t |> ggplot(aes(x=x)) +
  geom_line(aes(y=y1)) +
  geom_line(aes(y = y2))

Is this what you're after?

> build <- ggplot_build(z)
> build$layout$panel_scales_y
 Range:  -2.58 -- 4.86
 Limits: -2.58 -- 4.86

> build$layout$panel_scales_x
 Range:  -1.54 --  2.4
 Limits: -1.54 --  2.4


> build$layout$panel_scales_y[[1]]$range$range
[1] -2.576292  4.856033
1 Like

Thanks @williaml . That is exactly what I wanted to know.

It does the job, but I don't really understand what's going on. Perchance could you add a bit of further explanation?

No worries. It is all in ggplot2::ggplot_build(), which:

takes the plot object, and performs all steps necessary to produce an object that can be rendered. This function outputs two pieces: a list of data frames (one for each layer), and a panel object, which contain all information about axis limits, breaks etc.

From there I am just accessing parts in the panels. Some of those are list objects, where you need to access the elements.

Build ggplot for rendering. — ggplot_build • ggplot2 (

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.