关闭散点图并仅打印回归线

时间:2017-10-13 18:55:34

标签: r plot non-linear-regression

我试图将回归曲线拟合到我的数据中。我的代码生成了我想要的绘图和曲线,但是,我不需要散点图 - 只需要线。如果我注释掉情节,我的代码就失败了。有没有办法(绕过,关闭,隐藏)散点图?

enter image description here

最终,我需要比较我的图表上的多个回归曲线,散点图会分散注意力。此外,我的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)

1 个答案:

答案 0 :(得分: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)) 

拟合度:(因为用户20650指出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)

enter image description here

添加另一条曲线:

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)

enter image description here

编辑:根据user20650建议(由于poly和nls曲线相同,因此确实不需要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))

enter image description here