2017-10-13 87 views
1

我正在嘗試將回歸曲線擬合到我的數據中。我的代碼生成我想要的繪圖和曲線,但是,我不需要散點圖 - 只有線條。如果我將情節註釋掉,我的代碼就會失敗。有沒有辦法(繞過,關閉,隱藏)散點圖?關閉散點圖並僅打印迴歸線

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) 
+2

嘗試加入'TYPE = 「N」'...'圖(X,Y,TYPE = 「N」,...'和NLS犯規返回R^2,因爲它沒有道理(雖然我認爲有一些軟件包可以)。也就是說,你的模型不是非線性的,你可以用'lm'來適應它 – user20650

回答

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

plot(根本不需要調用繪圖 - 添加其他曲線,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提議(是真的不因爲所述聚和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