[R] Help with lattice panel function

Naresh Gurbuxani naresh_gurbuxani at hotmail.com
Wed Apr 29 13:09:19 CEST 2015


I want to plot multiple variables in xyplot, but plot loess trend for only one of these variables.  My problem is that the last command below does not give the desired result. 
Any help will be gratefully received.
Thanks,Naresh
my.df <- data.frame(date = as.numeric(as.Date("2015-01-01")) + 0:49, x = rnorm(50))
my.df$date <- as.Date(my.df$date, origin = as.Date("1970-01-01"))


library(zoo)
x <- zoo(my.df[,"x"], my.df[,"date"])
max.x <- rollapply(x, 10, max, align = "right")
x <- merge(x, max.x)
my.newdf <- data.frame(x)
my.newdf$date <- as.Date(row.names(my.newdf))


library(lattice)# This works as expected
xyplot(x + max.x ~ date, data = my.newdf, type = "l", 
   auto.key = list(columns = 2, points = FALSE, lines = TRUE), ylab = "x")
   # This does not work
xyplot(x ~ date, data = my.newdf, y2 = max.x, ylab = "x",
   panel = function(x, y, x2, ...){
   	panel.xyplot(x, y, type = "l")
   	panel.loess(x, y, lty = 2)
   	panel.xyplot(x, y2, type = "l")
   })      		 	   		  
	[[alternative HTML version deleted]]



More information about the R-help mailing list