【问题标题】:extract equation used to get the best fit using Lattice (panel.smoother) or ggplot使用 Lattice (panel.smoother) 或 ggplot 提取用于获得最佳拟合的方程
【发布时间】:2016-02-19 13:31:24
【问题描述】:

我有 100 多个具有相似数据的文件,它们遵循几乎相同的趋势。我已经设法获得了所有这些的最佳拟合,但现在我想将其与理论论证进行比较。换句话说,我想为我使用实验数据生成的最佳拟合曲线生成一个方程;该方程适用于特定范围内的任何随机值,并产生与以前相似的曲线,当然有一些错误。

代码:

set.seed(42)
x <-sort(round(runif(10,0,53)))   ## random x values
y <- runif(10,0,400)              ## random y values
data1 <-  data.frame(y=y,x=x)     ## creating a data frame

现在我要么使用lattice,如下所示:

library(lattice)
library(latticeExtra)
xyplot(y ~ x,data=data1,par.settings = ggplot2like(),
                   panel = function(x,y,...){
                     panel.xyplot(x,y,...)
                   })+ layer(panel.smoother(y ~ x, se = FALSE, span = 0.5))

ggplot如下:

library(ggplot2)
ggplot(data1, aes(x=x, y=y)) + geom_point() + geom_smooth(se = FALSE)

我只是想知道它的方程或者可能只是曲线的几个参数(系数、标准误差值等)

【问题讨论】:

    标签: r ggplot2 regression lattice stat


    【解决方案1】:

    平滑器通常比您想象的要复杂。它们通常仅在局部定义,因此没有全局方程,因为可能存在多项式拟合。 panel.smoother 函数默认使用loess 平滑器,并且从您对xyplot 的调用返回的对象中没有等式。而是调用保存在面板节点的lay 节点中的panel.smoother 函数:

     myplot <- xyplot(y ~ x,data=data1,par.settings = ggplot2like(),
                   panel = function(x,y,...){
                     panel.xyplot(x,y,...)
                   })+ layer(panel.smoother(y ~ x, se = FALSE, span = 0.5))
     get('lay', envir = environment(myplot$panel))
    #-------------
    [[1]]
    expression(panel.smoother(y ~ x, se = FALSE, span = 0.5))
    attr(,"under")
    [1] FALSE
    attr(,"superpose")
    [1] FALSE
    
    attr(,"class")
    [1] "layer"   "trellis"
    

    这向您展示了评估该表达式时产生的结果:

    mysmooth <- loess(y~x)
    str(mysmooth)
    #--------
    List of 17
     $ n        : int 10
     $ fitted   : num [1:10] 176 312 275 261 261 ...
     $ residuals: Named num [1:10] 6.78 -24.43 98.8 -159.25 -75.9 ...
      ..- attr(*, "names")= chr [1:10] "1" "2" "3" "4" ...
     ----------- omitting remaider of output------------
    

    我使用了xyplot-smoother,因为尝试在 ggplot 函数结果中查找代码详细信息甚至比应用于 lattice 对象的任务更复杂。这个故事的寓意:如果您想要一个具有特定复杂性和可定义特性的函数,请使用合适的样条函数,例如生存中的splinepsspline 或rms 中的rcs

    【讨论】:

    • 非常感谢。在您发帖之前,我实际上并不了解 Smoother 的功能。 str() 的结果正是我想要的。使用这些值,我想我可以创建我需要的方程式。 splines() 似乎也可以正常工作。再次感谢您。
    猜你喜欢
    • 2019-01-17
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多