使用Lattice(panel.smoother)或ggplot提取用于获得最佳拟合的方程式

时间:2015-11-18 00:04:54

标签: r ggplot2 regression lattice stat

我有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)

enter image description here

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

1 个答案:

答案 0 :(得分:4)

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

 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 - 更顺畅,因为尝试在ggplot函数中找到代码细节 - 结果比应用于晶格对象的任务更复杂。这个故事的道德:如果你想要一个特定复杂性和可定义特征的函数,那么使用合适的样条函数,例如生存中的splinepsspline或有效值中的rcs