Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

I have an object from ggplot2, say myPlot, 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. findFn (from sos) and Google don't seem to be turning up relevant results, other than how to set the axes' ranges.

like image 700
Iterator Avatar asked Oct 09 '11 17:10

Iterator


People also ask

How do you set axis ranges in R?

To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.

How do I get Ggplot data?

To get values actually plotted you can use function ggplot_build() where argument is your plot. This will make list and one of sublists is named data . This sublist contains dataframe with values used in plot, for example, for histrogramm it contains y values (the same as count ).

What is Ggplot_build?

Description. ggplot_build() 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.

What is ggplot2 scale?

Scales in ggplot2 control the mapping from data to aesthetics. They take your data and turn it into something that you can see, like size, colour, position or shape. They also provide the tools that let you interpret the plot: the axes and legends.


1 Answers

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 
like image 141
Paul Hiemstra Avatar answered Sep 23 '22 06:09

Paul Hiemstra