Monday, September 26, 2011

Overlay plots in R (or "Is there a command equivalent to 'hold on' of MATLAB in R?")

So used to the simple method of plotting graphs in MATLAB, I've run into a couple of quirky situations while using R. As the tile of this post describes it, the latest problem I've had was when I was trying to overlay different plots on the same graph.

In MATLAB, this is easy: we just plot, then issue a 'hold on', then plot again. Done!

In R, I've finally found a solution: between two calls to plot, I set a 'par(new=T)'. Additionally one should specify the xlim as well as the ylim=c(y1,y2) in each call to plot() to get proper matching of the overlaid plots.

Quick example (YMMV):


f1.range = range(f1.results)
f2.range = range(f2.results)
plot(f1, broken = TRUE, bcontrol = list(style = "gap"), ylim = range(f1.range, f2.range))
par(new=T)
plot(f2, ylim = range(f1.range, f2.range), pch=24)

2 comments:

  1. you should also make the axes invisible for the second plot as it will plot them twice

    ReplyDelete