6

我想在格子中的一个面板上叠加多个组,并想要独立的回归线。

通过使用条件因子获得多个面板相当容易,每个面板都有一条回归线:

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
)

在此处输入图像描述

为叠加的 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')
)

在此处输入图像描述

但这不是我需要的。我会输入一个答案,但它似乎很乱。也许这就是野兽的本性。

我正在寻找更容易理解的东西。Lattice 是首选,但也可以接受一个好的 ggplot 解决方案。如果不清楚,我正在制作供 Excel 用户使用的绘图。

4

3 回答 3

9

这是我想出的:

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

在此处输入图像描述

于 2013-01-06T18:57:58.753 回答
8

您可以使用type参数让 Lattice 为您完成面板工作

xyplot(Petal.Width  ~ Petal.Length, groups = Species, data = iris, 
     type = c('p','r','g'),  
     auto.key = list(title='Species', space='right'))
于 2013-04-02T08:35:39.150 回答
3

看来您可以将其简化为

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')
)
于 2014-11-12T09:28:42.153 回答