[R] ow to apply a panel function to each of several data series plotted on the same graph in lattice
David Wyllie
David.Wyllie at ndm.ox.ac.uk
Fri Jun 18 09:45:26 CEST 2010
Hi
is it possible to fit a trend line (or some other panel function) through each of multiple data series plotted on the same graph? Specifically, while one can do something like
xyplot(a+b+c~x)
which plots three series, a,b & c, but can one automatically fit lines through each of them?
I suppose one could generate three more variables afit, bfit, and cfit with a model & predict and then plot them, but wondered if there was an easier way.
Thank you for any advice. Here is an example:
# use an example panel function using smooth.spline; however, the issue relates to all panel functions
# a panel function to fit smoothed lines through data
panel.smooth.spline <- function(x, y,
w=NULL, df, spar = NULL, cv = FALSE,
lwd=plot.line$lwd, lty=plot.line$lty,col, col.line=plot.line$col,
type, horizontal=FALSE,... )
{
# Deepayan Sarkar code from: http://www.mail-archive.com/r-help@r-project.org/msg39654.html
x <- as.numeric(x)
y <- as.numeric(y)
ok <- is.finite(x) & is.finite(y)
if (sum(ok) < 1)
return()
if (!missing(col)) {
if (missing(col.line))
col.line <- col
}
plot.line <- trellis.par.get("plot.line")
if (horizontal) {
spline <-
smooth.spline(y[ok], x[ok],
w=w, df=df, spar = spar, cv = cv, ...)
panel.lines(x = spline$y, y = spline$x, col = col.line,
lty = lty, lwd = lwd, ...)
}
else {
spline <-
smooth.spline(x[ok], y[ok],
w=w, df=df, spar = spar, cv = cv, ...)
panel.lines(x = spline$x, y = spline$y, col = col.line,
lty = lty, lwd = lwd, ...)
}
}
# a composite function combining the xyplot and smooth.spline functions
panel.composite<-function(x,y,groups, subscripts, ...) {
panel.xyplot(x,y,...)
panel.smooth.spline(x,y,...)
}
# generate mock data; this comprises three data series, a,b,c with means of about 5,35, and 105.
test <- data.frame(
a = runif(100, min=0, max=10),
b = 30+runif(100, min=0, max=10),
c = 100+runif(100, min=0, max=10),
x = 1:100)
# illustrate data
xyplot(a + b + c ~ x, data = test, type = "p", auto.key=TRUE)
# plot with fits .. but actually only one fit
xyplot(
a + b + c ~ x,
panel=panel.composite,
data = test,
type = "p",
auto.key=TRUE)
More information about the R-help
mailing list