[R] Plot 2 time series with different y axes (left and right)
Ajay Shah
ajayshah at mayin.org
Wed Mar 17 03:00:17 CET 2004
Petr Pikal said:
> I am not really a R specialist but for this task I use function:
and he pasted his code into the email. I reindented the code, and
wrote a fragment to experiment with it. Here it is:
---------------------------------------------------------------------------
plot.yy <- function(x, yright, yleft,
yleftlim=NULL, yrightlim = NULL,
xlab = NULL, yylab=c("",""),
pch=c(1,2), col=c(1,2),
linky=F, smooth=0,
lwds=1, length=10, format="%d-%H:%M", ...
)
{
par(mar=c(5,4,4,2),oma=c(0,0,0,3))
plot(x, yright, ylim=yrightlim, axes=F,ylab="", xlab=xlab,
pch=pch[1],col=col[1], ...)
axis(4,pretty(range(yright,na.rm=T),10),col=col[1])
if (linky) lines(x,yright,col=col[1], ...)
if (smooth!=0) lines(supsmu(x,yright,span=smooth),col=col[1], lwd=lwds, ...)
if(yylab[1]=="")
mtext(deparse(substitute(yright)),side=4,outer=T,line=1, col=col[1], ...)
else
mtext(yylab[1],side=4,outer=T,line=1, col=col[1], ...)
par(new=T)
plot(x,yleft, ylim=yleftlim, ylab="", axes=F ,xlab=xlab,
pch=pch[2],col=col[2], ...)
box()
axis(2,pretty(range(yleft,na.rm=T),10),col=col[2], col.axis=col[2])
if (is.null(class(x)))
axis(1,pretty(range(x,na.rm=T),10))
else {
l<-length(x)
axis(1,at=x[seq(1,l,length=length)],
labels=format(as.POSIXct(x[seq(1,l,length=length)]),
format=format))
}
if(yylab[2]=="")
mtext(deparse(substitute(yleft)),side=2,line=2, col=col[2], ...)
else
mtext(yylab[2],side=2,line=2, col=col[2], ...)
if (linky)
lines(x,yleft,col=col[2], lty=2, ...)
if (smooth!=0)
lines(supsmu(x,yleft,span=smooth),col=col[2], lty=2, lwd=lwds, ...)
}
# I wrote some code in order to try out the plot.yy() function --
x = 1990:2000;
y1 = 100*rnorm(11)
y2 = 200*rnorm(11)
plot.yy(x, y1, y2, yylab=c("Y axis 1", "Y axis 2"),
linky=T, smooth=0,
lwds=3, length=10)
---------------------------------------------------------------------------
Thanks! This gave me lots of ideas.
When I run this code, I get the error --
Error in as.POSIXct.default(x[seq(1, l, length = length)]) :
Don't know how to convert `x[seq(1, l, length = length)]' to class "POSIXct"
Execution halted
I also find that one of the two series is not `linked' (in your
notation). I also find that the y label "Y axis 2" does not appear.
Any ideas?
Thanks again,
-ans.
--
Ajay Shah Consultant
ajayshah at mayin.org Department of Economic Affairs
http://www.mayin.org/ajayshah Ministry of Finance, New Delhi
More information about the R-help
mailing list