Skip to content
Prev 179507 / 398503 Next

Add trend line to XYPlot using a subset of the original data

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)
or
   pkyr<-x>1927
   panel.lines(x[pkyr],exp(predict.lm(lm(log(y[pkyr])~x[pkyr]))),col=4)
or
   pkyr<-x>1927
   my.lm<-lm(log(y[pkyr])~x[pkyr])
   panel.lines(x[pkyr],exp(x[pkyr]*(my.lm$coef[2])+my.lm$coef[1]),col=3)
or
   panel.lines(x[pkyr],exp(x[pkyr]*(-my.lm$coef[2])+my.lm$coef[1]),col=3)  #
this doesn't plot any line

And other variations on subsetting the data and calculating the slope.

If I create the same using the plot command, the slope of the trend based on
the subset of the data is correct. 

pck<-!is.na(pkdat$X9444500)
plot(X9444500~WY,data=pkdat[pck,],xlim=c(1900,2020),ylab="TEST",
xlab="",ylim=c(100,100000),yaxp=c(100,100000,1),las=1,tck=.02,log="y",yaxs='i',xaxs='i',mgp=c(3,.5,0))
lines(pkdat$WY[pck],exp(predict.lm(lm(log(pkdat$X9444500[pck])~pkdat$WY[pck]))),col=3)
pkyr<-pkdat$WY[pck]>1927
lines(pkdat$WY[pck][pkyr],exp(predict.lm(lm(log(pkdat$X9444500[pck][pkyr])~pkdat$WY[pck][pkyr]))),col=2)
my.lo2<-loess(log(pkdat$X9444500[pck])~pkdat$WY[pck],span=.7,degree=1)
lines(pkdat$WY[pck],exp(predict(my.lo2)),col=6)


I would like to use the xyplot command though because of other graphics
control options and other similar graphs for the same project that were
created using xyplot.

Any suggestions on using a subset of x and y in the xyplot?

Thank you