Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get xlim from a plot in R

Tags:

plot

r

I want an hist and a density on the same plot, I'm trying this:

myPlot <- plot(density(m[,1])), main="", xlab="", ylab="")
par(new=TRUE)

Oldxlim <- myPlot$xlim
Oldylim <- myPlot$ylim

hist(m[,3],xlim=Oldxlim,ylim=Oldylim,prob=TRUE)

but I can't access myPlot's xlim and ylim.

Is there a way to get them from myPlot? What else should I do instead?

like image 681
jimifiki Avatar asked Dec 12 '12 15:12

jimifiki


2 Answers

Using par(new=TRUE) is rarely, if ever, the best solution. Many plotting functions have an option like add=TRUE that will add to the existing plot (including the plotting function for histograms as mentioned in the comments).

If you really need to do it this way then look at the usr argument to the par function, doing mylims <- par("usr") will give the x and y limits of the existing plot in user coordinates. However when you use that information on a new plot make sure to set xaxs='i' or the actual coordinates used in the new plot will be extended by 4% beyond what you specify.

The functions grconvertX and grconvertY are also useful to know. They could be used or this purpose, but are probably overkill compared to par("usr"), but they can be useful for finding the limits in other coordinate systems, or finding values like the middle of the plotting region in user coordinates.

like image 87
Greg Snow Avatar answered Sep 28 '22 04:09

Greg Snow


Have you considered specifying your own xlim and ylim in the first plot (setting them to appropriate values) then just using those values again to set the limits on the histogram in the second plot?

Just by plotting density on its own you should be able to work out sensible values for the minimum and maximum values for both axes then replace xmin, xmax, ymin and ymax for those values in the code below.

something like;

myPlot <- plot(density(m[,1])), main="", xlab="", ylab="", xlim =c(xmin, xmax), ylim = c(ymin, ymax)

par(new=TRUE)

hist(m[,3],xlim=c(min, max),ylim=c(min, max),prob=TRUE)
like image 26
Adam Kimberley Avatar answered Sep 28 '22 04:09

Adam Kimberley