通过xyplot拟合平滑

Fitting smooth through xyplot

这道题看起来很简单,但是我一直没弄明白怎么做。我正在尝试通过纵向数据集拟合一条平滑线,如下面的代码所示

library(nlme)
xyplot(conc ~ Time, data = Theoph, groups = Subject, type = c("l", "smooth"))

输出不是我想要的,并且有多个警告。我想平滑地拟合整个数据。作为奖励,如果有人还可以展示如何使用 ggplot 执行此操作,那就太好了。

您可以使用 latticeExtra 包为您的第一个 treillis 对象添加平滑度

library(nlme)
library(ggplot2)
library(lattice)
library(latticeExtra)

xyplot(conc ~ Time, data = Theoph, groups = Subject, type = "l") +
  layer(panel.smoother(..., col = "steelblue"))

这里是同一张图的 ggplot2 版本

ggplot(data = Theoph, aes(Time, conc)) +
  geom_line(aes(colour = Subject)) +
  geom_smooth(col = "steelblue")

要将各个主题绘制为单独的线和点,但绘制整体平滑,请使用显示的两种格子方法或最后的经典图形和动物园方法。另请注意,我们需要对时间点进行排序以产生整体平滑并且未使用 nlme 包。另请注意,问题中的代码没有给出错误——只有警告。

1) trellis.focus/trellis.unfocus 我们可以使用trellis.focus/trellis.unfocus来增加整体的平滑度:

library(lattice)

xyplot(conc ~ Time, groups = Subject, data = Theoph, type = "o")

trellis.focus("panel", 1, 1)
o <- order(Theoph$Time)
panel.xyplot(Theoph[o, "Time"], Theoph[o, "conc"], type = "smooth", col = "red", lwd = 3)
trellis.unfocus()

2) 面板函数 第二种方法是定义一个合适的面板函数:

library(lattice)

o <- order(Theoph$Time)

xyplot(conc ~ Time, groups = Subject, data = Theoph[o, ], panel =   
  function(x, y, ..., subscripts, groups) {
     for (lev in levels(groups)) {
         ok <- groups == lev
         panel.xyplot(x[ok], y[ok], type = "o", col = lev)
     }
     panel.xyplot(x, y, type = "smooth", col = "red", lwd = 3)
})

其中任何一个都给出了以下输出。注意整体平滑的就是粗红线。

(图表后续)

3) zoo/classic graphics 这是一个使用 zoo 包和经典图形的解决方案。

library(zoo)

Theoph.z <- read.zoo(Theoph[c("Subject", "Time", "conc")], 
   index = "Time", split = "Subject")

plot(na.approx(Theoph.z), screen = 1, col = 1:nlevels(Theoph$Subject))

o <- order(Theoph$Time)
lo <- loess(conc ~ Time, Theoph[o, ])
lines(fitted(lo) ~ Time, Theoph[o,], lwd = 3, col = "red")