Superposed xyplot Panels with Grouped Regression Lines

孤者浪人 提交于 2019-12-18 13:35:00

问题


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.


回答1:


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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/14185600/superposed-xyplot-panels-with-grouped-regression-lines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!