[R] Multipanel weighted regression lines.
Andrew C. Ward
s195404 at student.uq.edu.au
Tue Jul 15 03:32:45 CEST 2003
Dear Kevin,
If you look at the examples under ?xyplot, you'll get some idea
about using panel functions. In your case, assume your data frame
has variables x, y, w (for weight), G (for panel) and g (for sub-
group). You could plot this using something like the following
clumsy effort:
x <- rnorm(500)
y <- 0.9*x + sqrt(1-0.9*0.9)*rnorm(500)
g <- sample(x=1:2, size=500, replace=TRUE)
G <- sample(x=c("A", "B", "C"), size=500, replace=TRUE)
w <- runif(500)
tmp <- data.frame(x=x, y=y, w=w, g=g, G=G)
#
xyplot(y ~ x | G, data=tmp, groups=g, weights=w,
panel=function(x,y,groups,subscripts=subscripts,
weights,...) {
t1 <- unique(groups)
for (i in 1:length(t1)) {
w <- is.element(groups[subscripts], t1[i])
lpoints(x[w], y[w], pch=i, col=i)
panel.abline(lm(y[w] ~ x[w], weights=(weights,
[subscripts])[w]), lty=i, col=i)
}
}, key=list(space="top", columns=2, points=list(pch=1:2,
col=1:2), text=list(paste("Group", 1:2),
col=1:2)))
Regards,
Andrew C. Ward
CAPE Centre
Department of Chemical Engineering
The University of Queensland
Brisbane Qld 4072 Australia
andreww at cheque.uq.edu.au
Quoting Kevin Brown <kevin.brown at mail.mcgill.ca>:
> Dear R-users,
>
> I am trying to create a multipanel scatter plot which displays
> weighted
> regression lines for each subgroup. I am having diffuculty
> figuring out
> how the Trellis multipanel plotting functions work, in general.
> Does
> someone know where there are some beginners examples on how to
> create
> and use panel.xxx functions in conjunction with the xyplot
> functions?
>
> Back to the matter at hand - There are two different ways that
> I could
> add these lines, I think.
>
> The first, and simplest would be to first find the coeffecients
> of the
> weighted regression line for each panel ( I can do this). Then
> I would
> add these coeffecients into a vector/matrix (i'm not sure what
> form of
> vector would be suitable) and add them to each panel (I do not
> know how
> to do this).
>
> The second way would be to fiddle around with the function
> below to add
> the "weights" to the lm function call. I do not know how to
> change this
> "plot.regression" function to do that.
>
> plot.regression = function(x,y)
> {
> panel.xyplot(x,y)
> panel.abline(lm(y~x))
> }
>
> xyplot(yg~xg | g, panel="plot.regression")
>
> Any help would be great!
> Thanks,
> Kevin Brown.
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>
More information about the R-help
mailing list