[R] Overlay of two graphs of different axes

Uwe Dippel udippel at uniten.edu.my
Mon Sep 13 07:54:02 CEST 2010


Though I have read quite a bit, and tried quite a bit, I have yet to 
find a nice way to overlay 2 or more curves in the same plot, with 
different ranges.
Here is simplified sample code to demonstrate the question:

 > plot(2*(seq(1,5)), type="l", axes=FALSE)
 > curve(2*(seq(1,5)), type="b", add=TRUE)
Error in curve(2 * (seq(1, 5)), type = "b", add = TRUE) :
   'expr' must be a function or an expression containing 'x'
 > axis(2)
 > curve(x^2, 1, 5, type="b", add=TRUE)
 > axis(4)

Firstly, as an aside, I am not clear why 'curve' has a different syntax 
compared to 'plot'. As a still beginner, I'd for one would be happy to 
add curves to a plot; curves of just different parameters. Though, I 
guess, there must be a good reason?

Mostly, however, I wonder how to plot a number of curves into an 
original plot, that re-defines the min/max from the most recent curve.

In the example that I constructed, axis(2) does exactly the expected thing.
What I want to do next, though, with the least effort, is to add another 
function in a manner that the added function is scaled, not according to 
the first function (plot), but to fit into the plotting area. (The 
example above overshoots the range).
Plus, how can I subsequently add the axis suitable to the most recent 
function? That is, how can I render axis(4) to displaying the scale for 
the second graph, created with 'curve'?

Thanks in advance,

Uwe



More information about the R-help mailing list