Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Superposed xyplot Panels with Grouped Regression Lines

Tags:

r

lattice

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
)

enter image description here

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')
)

enter image description here

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.

like image 345
Matthew Lundberg Avatar asked Jan 06 '13 18:01

Matthew Lundberg


3 Answers

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')
)

enter image description here

like image 130
Matthew Lundberg Avatar answered Nov 14 '22 04:11

Matthew Lundberg


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'))
like image 8
Gabra Avatar answered Nov 14 '22 06:11

Gabra


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')
)
like image 3
Andreas K Avatar answered Nov 14 '22 05:11

Andreas K