[R] Overlay of two graphs of different axes

David Winsemius dwinsemius at comcast.net
Mon Sep 13 14:06:53 CEST 2010


On Sep 13, 2010, at 1:54 AM, Uwe Dippel wrote:

> 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.

The different axes could be a problem but if you construct both with  
predefined coordinates systems and scale appropriately it should work  
out. See the twoord.plot function  in plotrix.

> Here is simplified sample code to demonstrate the question:
>
> > plot(2*(seq(1,5)), type="l", axes=FALSE)

? lines

  lines(1.5*(seq(2,5)), type="b")


> > 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?

curve is like abline in that it draws from left x range to right x  
range.
>
> 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.

lines() or segments()

>
> 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'?

There are many worked examples in the archives, as well as canned  
solutions in widely used packages.

>

-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list