Scribbling ….

How to get axis limit in R

Posted in practical R by avan on December 12, 2009

One annoying thing in R (for me as a Matlab user) is retrieving the axis limit. In Matlab, you can simply call get(gca,'XLim') or get(gca,'YLim'). It’s so obvious.

The manual of ?plot command in R does not have limit options, but you can call, for instances (see the figure on the left):

> plot(Nile,ylim=c(0,1500))

It’s because the xlim and ylim are optional arguments in the plot.default() command. The plot() is a generic name, which will call other specialized plot commands depending the given data/object.

Here’s the annoying part. You cannot find xlim or ylim options in the list of graphic parameters by the par() command. Also you cannot adjust these limit yourself in some specialized plot commands. Sometimes you need to adjust these parameters yourself. So how can you do that?

Well, these axis limit options are actually listed in the par() parameters, but under strangely different name. It took me quite some time to find it. You can ask the boundary limit of an axis with usr command. So for instances (I took this example from the clip help), if you have this histogram plot:

> x = rnorm(1000)
> hist(x, xlim=c(-4,4))

You can ask and use its axis limit, for instances for applying the clipping region:

> usr = par("usr")
> clip(usr[1], -1, usr[3], usr[4])
> hist(x, col = 'red', add = TRUE)
> clip(1, usr[2], usr[3], usr[4])
> hist(x, col = 'blue', add = TRUE)
>"clip", as.list(usr))  # reset to plot region

That’s annoying, because the name of usr has nothing to do with axis limit. Again to note that this parameter is not the same as the tick mark intervals that you see in the axis. You must use another strange par parameters: xaxp and yaxp, i.e., that give the tick mark parameters. Why can’t R use XTickMarks or YTickMarks like in Matlab that are more easy to remember?

So here are the three parameter returns for the above histogram plot:

> par('usr')
[1]  -4.32   4.32  -8.12 211.12
> par('xaxp')
[1] -4  4  4
> par('yaxp')
[1]   0 200   4

Tagged with: ,

One Response

Subscribe to comments with RSS.

  1. […] is another nice post about the ‘usr’ option to […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: