绘制分段回归线

机器算法验证 r 数据可视化 回归
2022-03-28 21:32:58

有没有办法像这样绘制分段模型的回归线,而不是使用lines单独绘制每个段,或者使用geom_smooth(aes(group=Ind), method="lm", fill=FALSE)

m.sqft <- mean(sqft)
model <- lm(price~sqft+I((sqft-m.sqft)*Ind))
# sqft, price: continuous variables, Ind: if sqft>mean(sqft) then 1 else 0

plot(sqft,price)
abline(reg = model)
Warning message:
In abline(reg = model) :
  only using the first two of 3regression coefficients

谢谢你。

1个回答

我知道如何轻松做到这一点的唯一方法是从模型中sqft预测并绘制预测。没有通用abline或类似的方法。您还可以查看适合这些模型并为您提供绘图基础设施的分段包。

通过预测和基本图形来做到这一点。首先,一些虚拟数据:

set.seed(1)
sqft <- runif(100)
sqft <- ifelse((tmp <- sqft > mean(sqft)), 1, 0) + rnorm(100, sd = 0.5)
price <- 2 + 2.5 * sqft
price <- ifelse(tmp, price, 0) + rnorm(100, sd = 0.6)
DF <- data.frame(sqft = sqft, price = price,
                 Ind = ifelse(sqft > mean(sqft), 1, 0))
rm(price, sqft)
plot(price ~ sqft, data = DF)

拟合模型:

mod <- lm(price~sqft+I((sqft-mean(sqft))*Ind), data = DF)

生成一些数据来预测和预测:

m.sqft <- with(DF, mean(sqft))
pDF <- with(DF, data.frame(sqft = seq(min(sqft), max(sqft), length = 200)))
pDF <- within(pDF, Ind <- ifelse(sqft > m.sqft, 1, 0))
pDF <- within(pDF, price <- predict(mod, newdata = pDF))

绘制回归线:

ylim <- range(pDF$price, DF$price)
xlim <- range(pDF$sqft, DF$sqft)
plot(price ~ sqft, data = DF, ylim = ylim, xlim = xlim)
lines(price ~ sqft, data = pDF, subset = Ind > 0, col = "red", lwd = 2)
lines(price ~ sqft, data = pDF, subset = Ind < 1, col = "red", lwd = 2)

您可以将其编码为一个简单的函数 - 您只需要前面两个代码块中的步骤 - 您可以使用它来代替abline

myabline <- function(model, data, ...) {
    m.sqft <- with(data, mean(sqft))
    pDF <- with(data, data.frame(sqft = seq(min(sqft), max(sqft),
                                            length = 200)))
    pDF <- within(pDF, Ind <- ifelse(sqft > m.sqft, 1, 0))
    pDF <- within(pDF, price <- predict(mod, newdata = pDF))
    lines(price ~ sqft, data = pDF, subset = Ind > 0, ...)
    lines(price ~ sqft, data = pDF, subset = Ind < 1, ...)
    invisible(model)
}

然后:

ylim <- range(pDF$price, DF$price)
xlim <- range(pDF$sqft, DF$sqft)
plot(price ~ sqft, data = DF, ylim = ylim, xlim = xlim)
myabline(mod, DF, col = "red", lwd = 2)

通过分段

require(segmented)
mod2 <- lm(price ~ sqft, data = DF)
mod.s <- segmented(mod2, seg.Z = ~ sqft, psi = 0.5,
                   control = seg.control(stop.if.error = FALSE))
plot(price ~ sqft, data = DF)
plot(mod.s, add = TRUE)
lines(mod.s, col = "red")

有了这些数据,它不会估计 处的断点mean(sqft),但该包中的plot和方法可能会帮助您实现比直接从拟合模型为您完成这项工作lines更通用的东西。myablinelm()

编辑:如果要分段以估计断点的位置,则将'psi'参数设置为NA

mod.s <- segmented(mod2, seg.Z = ~ sqft, psi = NA,
                   control = seg.control(stop.if.error = FALSE))

然后segmented将尝试,K = 10的分位数sqftK设置为seg.control(),默认为10查看?seg.control更多。