mario
mario

Reputation: 11

Turn off scatter plot and print only regression line

I'm trying to fit a regression curve to my data. My code generates the plot and curve that I want, however, I don't need the scatter plot--only the line. If I comment out the plot, my code fails. Is there a way to (bypass, turn-off, hide) the scatter plot?

enter image description here

Ultimately, I will need to compare multiple regression curves on my graph and the scatter charts become distracting. Also, my R2 shows NULL. Is there a coefficient for R2?

Code below.

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

Upvotes: 1

Views: 467

Answers (1)

missuse
missuse

Reputation: 19716

Here is an example with cars data

Fit:

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

goodness of fit: (as user20650 pointed out R2 makes little sense for a non linear model, perhaps a better metric is 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 (no need to call plot at all - add other curves with 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

to add another curve:

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

EDIT: as per user20650 suggestion (the nls is really not needed since the poly and nls curves are the same)

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

Upvotes: 1

Related Questions