【问题标题】:Turn off scatter plot and print only regression line关闭散点图并仅打印回归线
【发布时间】:2018-03-25 23:20:33
【问题描述】:

我正在尝试为我的数据拟合一条回归曲线。我的代码生成了我想要的图和曲线,但是,我不需要散点图——只需要线。如果我注释掉情节,我的代码就会失败。有没有办法(绕过、关闭、隐藏)散点图?

最终,我需要比较图表上的多条回归曲线,而散点图会分散注意力。另外,我的 R2 显示为 NULL。 R2有系数吗?

代码如下。

    # get underlying plot
    y <- dataset$'Fuel Consumed 24h'
    x <-dataset$'Performance Speed'
    plot(x, y, xlab = "Performance Speed", ylab = "24h Fuel Consumption")

    # polynomial
    f <- function(x,a,b,d) {(a*x^2) + (b*x) + d}
    fit <- nls(y ~ f(x,a,b,d), start = c(a=1, b=1, d=1)) 
    co <- round(coef(fit), 2)
    r2 <- format(summary(fit)$r.squared, digits = 3)
    curve(f(x, a=co[1], b=co[2], d=co[3]), add = TRUE, col="red", lwd=2) 
    eq <- paste0("Fuel = ", co[1], "PS^2 ", ifelse(sign(co[2]) == 1, " + ", " - "), abs(co[2]), "PS +", co[3],  "   R2 = ", r2)

    # print equation
    mtext(eq, 3, line =-2)
    mylabel = bquote(italic(R)^2 == .(format(r2, digits = 3)))
    text(x = 1, y = 2.5, r2)

【问题讨论】:

  • 尝试添加type="n" ... plot(x, y, type="n", ...,nls 不会返回 r^2,因为它没有意义(尽管我认为有些软件包可以这样做)。也就是说,你的模型不是非线性的,你可以用lm

标签: r plot non-linear-regression


【解决方案1】:

这是汽车数据的示例

适合:

data(cars)
f <- function(x,a,b,d) {(a*x^2) + (b*x) + d}
fit <- nls(dist ~ f(speed,a,b,d), data = cars, start = c(a=1, b=1, d=1)) 

拟合优度:(正如 user20650 指出的那样,R2 对于非线性模型意义不大,也许更好的指标是 RMSE)

rmse <- function(error)
{
  sqrt(mean(error^2))
}
error <- predict(fit, cars) - cars$dist
rms  <- rmse(error)

eq <- paste0("Fuel = ", co[1], "PS^2 ", ifelse(sign(co[2]) == 1, " + ", " - "), abs(co[2]), "PS +", co[3],  "   RMSE = ", round(rms, 2))

绘图(根本不需要调用绘图 - 使用 add = T 添加其他曲线):

curve(f(x, a=co[1], b=co[2], d=co[3]), col="red", lwd=2, from = min(cars$speed), to = max(cars$speed)) 
mtext(eq, 3, line =-2)

添加另一条曲线:

f2 = function(x, a, b) {a + b*x}
co2 = coef(lm(dist ~ speed, data = cars))
curve(f2(x, a = co2[1], b = co2[2]), col="blue", lwd=2, add = T)

编辑:根据 user20650 的建议(实际上不需要 nls,因为 poly 和 nls 曲线是相同的)

co3 = coef(lm(dist ~ poly(speed, 2, raw=TRUE), data = cars))
curve(f3(x, a = co3[1], b = co3[2], c = co3[3]), col="grey", lty = 2,  lwd=2, add = T)
legend("topleft", legend = c("nls", "lm", "poly"), col = c("red", "blue", "grey"), lty =c(1,1,2))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 2021-02-06
    • 2012-06-27
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多