【问题标题】:Adding a custom LOESS panel to lattice plot in R在 R 中将自定义 LOESS 面板添加到晶格图
【发布时间】:2015-03-12 11:01:03
【问题描述】:

我正在尝试为我的绘图创建一个自定义的 LOESS 面板函数。基本上它应该做的与简单的panel.loesstype = "smooth" 相同。原因是稍后我想让它变得更复杂一些,用上面的方法不容易实现。但是,它失败了。

这是一个 MWE(其中一些大致基于 Sarkar 的 Lattice 书第 235 页的示例:

library(lattice)

set.seed(9)
foo <- rexp(100)
bar <- rexp(100)
thing <- factor(rep(c("this", "that"), times = 50))
d.f <- data.frame(foo = foo, bar = bar, thing = thing)

loess.c <- function(x) { 
  mod <- loess(foo ~ bar, data = x)
  return(mod)
}

panel.cloess <- function(x, n = 50, ...){ 
  panel.xyplot(x, ...)
  lfit  <- loess.c(x)
  xx <- do.breaks(range(x$x), n)
  yy <- predict(lfit, newdata = data.frame(bar = xx),
                se = TRUE)
  print(yy) # doesn't do anything
  panel.lines(x = xx, y = yy$fit, ...)
}

xyplot(foo ~ bar | thing, data = d.f,
       panel = panel.cloess)

结果是这样的:

显然,这是行不通的。我收到以下错误消息:Error using packet n numeric 'envir' arg not of length one。我调试它的尝试(例如使用 print(yy))效果不佳,所以我不知道从哪里开始寻找解决方案。

关于造成这种情况的任何想法?

【问题讨论】:

    标签: r panel lattice loess


    【解决方案1】:

    经过一些(小)修改后,我使用了这个脚本

    xyplot(foo ~ bar | thing, data = d.f, panel =  function(x,y){
        xx <- do.breaks(range(x), 49)
        mod <- loess(y~x)
        yy <- predict(mod, newdata = data.frame(foo=xx))
        panel.xyplot(x,y)
        panel.lines(x=xx, y= yy)
    })
    

    我更改了点数,因为有一些警告信息。它有效吗?这是您所期望的吗?

    【讨论】:

    • 是的,它有效。但我希望实际的 loess 调用在 lattice 的 xyplot 外部,因为它也将用于其他事情。
    • 嗯,你可以提取代码并像你的帖子一样使用它,但我不确定你使用的参数,而且你这样做的方式似乎有点复杂。
    • 现在看来很复杂,但以后有它的优点。不过,您的回答很好 - 我没有正确使用参数(xy)。似乎xy 是点的实际坐标,而我错误地认为x 是整个数据包。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-30
    相关资源
    最近更新 更多