[R] Add trend line to XYPlot using a subset of the original data
Deepayan Sarkar
deepayan.sarkar at gmail.com
Thu May 7 02:53:26 CEST 2009
On Wed, May 6, 2009 at 12:29 PM, kryberg <kryberg at usgs.gov> wrote:
>
> I've created an xyplot that I want to add a trend line to using a subset of
> the data.
>
> The xyplot is
>
> xyplot(X9444500~WY,data=mynewdata,xlim=c(1900,2020),ylab="TEST",
> xlab="",ylim=c(100,100000),scales=list(x=list(at=c(1900,1920,1940,1960,1980,2000,2020),axs="r",tck=-1),y=list(log=TRUE,tck=-100,at=c(100,1000,10000,100000))),
> panel=function(x,y,...) {
> panel.xyplot(x,y,col=1)
> panel.lines(x,exp(predict.lm(lm(log(y)~x))),col=4)
> panel.loess(x,y,span=.7,col=5)
> },sub="Figure X. Trends in ...",
> key=list(space="bottom",points=list(col=c(9,0,0,0),pch=1),lines=list(col=c(0,4,2,3),lty=c(1,1,1,1),lwd=c(2,2,2,2)),text=list(as.character(textlabs)),columns=3))
>
>
> That part works well, but I want to add a trend line using a subset of the
> data. The additional trend line always has the wrong slope. The slope of
> the line should be close to zero, but positive. It always plots close to
> zero, but negative.
>
> I've tried adding the following lines to the above
>
> panel.lines(x[21:98],exp(predict.lm(lm(log(y[21:98])~x[21:98]))),col=5)
Does this work better?
panel=function(x,y,...) {
panel.xyplot(x,y,col=1)
## panel.lines(x,exp(predict.lm(lm(log(y)~x))),col=4)
panel.lmline(lm(y ~ x), col=4)
panel.loess(x,y,span=.7,col=5)
panel.lmline(lm(y ~ x, subset = x > 1927), col=4)
}
Unlike your plot() example, y is already log-transformed in the panel function.
-Deepayan
More information about the R-help
mailing list