I want to superpose multiple groups on a single panel in lattice, and want independent regression lines.
It is fairly easy to get multiple panels, each with a regression line by using a conditioning factor:
xyplot(
Petal.Width ~ Petal.Length | Species,
data = iris,
panel = function(x, y, ...) {
panel.xyplot(x, y, ...)
panel.abline(lm(y~x), col='#0080ff')
},
grid = TRUE
)
It is also fairly easy to print a single regression for all of the points in a superposed xyplot:
xyplot(
Petal.Width ~ Petal.Length,
data = iris,
groups = Species,
panel = function(x, y, ...) {
panel.xyplot(x, y, ...)
panel.abline(lm(y~x))
},
grid = TRUE,
auto.key = list(title='Species', space='right')
)
But this is not what I need. I will enter an answer to this, but it seems messy. Perhaps that's just the nature of the beast.
I'm looking for something that is easier to understand. Lattice is preferred, but a good ggplot solution may be accepted as well. If it isn't clear, I'm making plots for consumption by Excel users.
Here is what I came up with:
xyplot(
Petal.Width ~ Petal.Length,
groups = Species,
data = iris,
panel = function(x, y, ...) {
panel.superpose(x, y, ...,
panel.groups = function(x,y, col, col.symbol, ...) {
panel.xyplot(x, y, col=col.symbol, ...)
panel.abline(lm(y~x), col.line=col.symbol)
}
)
},
grid = TRUE,
auto.key = list(title='Species', space='right')
)
You can let Lattice do the panel-stuff for you using the type argument
xyplot(Petal.Width ~ Petal.Length, groups = Species, data = iris,
type = c('p','r','g'),
auto.key = list(title='Species', space='right'))
It seems that you can simplify this to
xyplot(
Petal.Width ~ Petal.Length,
groups = Species,
data = iris,
panel = panel.superpose, # must for use of panel.groups
panel.groups=function(x, y, col, col.symbol, ...) {
panel.xyplot(x, y, col=col.symbol, ...)
panel.lmline(x, y, col.line=col.symbol)
},
grid = TRUE,
auto.key = list(title='Species', space='right')
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With