本文介绍了如何在coplot中的数据上绘制回归线或LOWESS线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在数据上绘制一条线(例如,拟合的回归线或非参数LOWESS线)通常会很有帮助.同样,当变量混淆时,绘制x1,y数据(按x2分层)通常会很有帮助.但是,我不太清楚如何使用?coplot .在格子中,这应该是很自然的,但是我可以似乎也没有弄清楚该怎么做.

It is often helpful to plot a line (e.g., a fitted regression line or a non-parametric LOWESS line) over data. Likewise, when variables are confounded, it is often helpful to plot x1, y data stratified by x2. However, I can't quite figure out how to combine both using ?coplot. This ought to be quite natural in lattice, but I can't seem to figure out how to do it there, either.

以下提供了一些可玩的数据:

The following provides some data to play with:

library(MASS)
set.seed(7422)
X <- mvrnorm(100, mu=c(5,5), Sigma=rbind(c(2.0, 1.9),
                                         c(1.9, 2.0) ) )
x1 <- X[,1];  x2 <- X[,2]
y <- 3 + .6*x1 - .4*x2 + rnorm(100)
m <- lm(y~x1+x2)
summary(m)$coefficients
#               Estimate Std. Error   t value     Pr(>|t|)
# (Intercept)  3.8281801  0.4022204  9.517619 1.476519e-15
# x1           0.5466495  0.2060269  2.653292 9.314673e-03
# x2          -0.4835804  0.2139542 -2.260205 2.604451e-02
windows()
  pairs(cbind(y, x1, x2))
xs <- seq(1.6, 9.2, by=.1)
windows()
  plot(y~x2)
  lines(xs, predict(m, data.frame(x1=5.2, x2=xs)), col="blue")
windows()
  coplot(y~x2|x1)
  ## doesn't work (lines on plot were drawn by hand)
  # lines(xs, predict(m, data.frame(x1=mean(x1[subscripts], x2=xs)), col="blue")
  # lines(lowess(y~x2, subset=x1[subscripts]), col="gray")

原始数据的散点图矩阵:

Scatterplot matrix of the raw data:

这是x2y的边际图,在数据顶部拟合了回归线和边际LOWESS线.对于那些在统计上并不精明的人来说,这看起来很奇怪.

Here is a marginal plot of x2 vs y, with fitted the regression line and a marginal LOWESS line plotted on top of the data. This will look weird to people who aren't statistically savvy.

这就是我的想法.这是一个coplot,具有回归模型和一条LOWESS线,适合各面板内部绘制的数据的每个层次.

This is what I have in mind. It's a coplot, with the regression model and a LOWESS line fitted to each stratum of the data plotted inside each panel.

推荐答案

要使用coplot进行此操作,您需要定义自己的 panel函数.默认函数是points,它仅绘制点,但是您可以使用简单函数添加回归线和最低曲线.

To do this with coplot, you need to define your own panel function. The default function is points which just plots the points, but you can add a regression line and a lowess curve with a simple function.

PointsWithReg = function(x, y, pch=20, col=1, ...) {
    points(x=x, y=y, col=col, pch=pch, type="p", ...)
    abline(lm(y ~ x))
    lines(lowess(x=x, y=y), col="blue")
}

coplot(y~x2|x1, panel=PointsWithReg, pch=16)

这篇关于如何在coplot中的数据上绘制回归线或LOWESS线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:21