I would like superimpose two scatter plots in R so that each set of points has its own (different) y-axis (i.e., in positions 2 and 4 on the figure) but the points appear superimposed on the same figure.
Is it possible to do this with plot?
Edit Example code showing the problem
# example code for SO question
y1 <- rnorm(10, 100, 20)
y2 <- rnorm(10, 1, 1)
x <- 1:10
# in this plot y2 is plotted on what is clearly an inappropriate scale
plot(y1 ~ x, ylim = c(-1, 150))
points(y2 ~ x, pch = 2)
update: Copied material that was on the R wiki at http://rwiki.sciviews.org/doku.php?id=tips:graphics-base:2yaxes, link now broken: also available from the wayback machine
Two different y axes on the same plot
(some material originally by Daniel Rajdl 2006/03/31 15:26)
Please note that there are very few situations where it is appropriate to use two different scales on the same plot. It is very easy to mislead the viewer of the graphic. Check the following two examples and comments on this issue (example1, example2 from Junk Charts), as well as this article by Stephen Few (which concludes “I certainly cannot conclude, once and for all, that graphs with dual-scaled axes are never useful; only that I cannot think of a situation that warrants them in light of other, better solutions.”) Also see point #4 in this cartoon …
If you are determined, the basic recipe is to create your first plot, set
par(new=TRUE)to prevent R from clearing the graphics device, creating the second plot withaxes=FALSE(and settingxlabandylabto be blank –ann=FALSEshould also work) and then usingaxis(side=4)to add a new axis on the right-hand side, andmtext(...,side=4)to add an axis label on the right-hand side. Here is an example using a little bit of made-up data:twoord.plot()in theplotrixpackage automates this process, as doesdoubleYScale()in thelatticeExtrapackage.Another example (adapted from an R mailing list post by Robert W. Baer):
Similar recipes can be used to superimpose plots of different types – bar plots, histograms, etc..