[R] Howto overlay two plots and save them in one pdf file?

Andy Bunn abunn at whrc.org
Thu Apr 21 14:12:03 CEST 2005


> Well for comparatative reason I would would like to subsume both plots 
> into a unifying plot and save them in one file.pdf.
> I tried to find an answer in FAQ and mailinglists archive, no luck. 
> Maybe did miss an appropiate answer to my question, so a pointer to 
> solve my problem woud be sufficient!

Do you mean a second y axis? If so then something like this would do it:

library(quantreg)
Age <- rnorm(50)
SBP <- Age * runif(50)

# LAD regression and related plot
rq(formula = SBP ~ Age)
f = coef(rq(SBP ~ Age))
pred = f[1] + f[2]*Age
# leave room for the second axis
pdf("junk.pdf")
par(mar = c(3,3,1,3), mgp = c(2, 1, 0))
plot (Age, SBP, ylab = "SBP: QR Fit")
lines (Age, pred)
par(new=T)
# OLS regression and related plot
Pred = lm(SBP ~ Age)
plot (Age, SBP, col = "blue", ylab = "", xlab = "", axes = F, pch = "+")
lines (Age,fitted(Pred), col = "blue")
axis(4, at=pretty(range(SBP)))
mtext("SBP: OLS Fit", 4, 2, col = "blue")
dev.off()

HTH, Andy




More information about the R-help mailing list