Luís Telles
Luís Telles

Reputation: 694

Why can't I fit a curve to this plot?

I am trying to fit a curve to this plot, but am having trouble.

Code:

library(ggplot2)

data <- data.frame(pressure = c(400, 200, 100, 50, 25, 12.5, 6.25, 3.125),
               volume = c(.25, .5, 1, 2, 4, 8, 16, 32))


plot(data, ylim = c(min(data[,2]), max(data[,2])), xlim = c(min(data[,1]), max(data[,1])),
 pch = 19, col = "firebrick")

lm_fit <- lm(data$pressure ~ poly(data$volume, 2, raw = TRUE))

lines(data$volume, predict (lm_fit, data.frame(x = data$volume)), col = "red")

Result:

Curve does not fit data

Upvotes: 1

Views: 67

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226057

Your main problem is using data$ inside your regression model: you should use just the names of the variables.

dd <- data.frame(pressure = c(400, 200, 100, 50, 25, 12.5, 6.25, 3.125),
                 volume = c(.25, .5, 1, 2, 4, 8, 16, 32))
lm_fit <- lm(pressure ~ poly(volume, 2, raw = TRUE),
             data=dd)

For a smoother curve, I computed the predicted value at a finer sequence of volume values:

pframe <- data.frame(volume=seq(0,30,length=51))
pframe$pressure <- predict(lm_fit,newdata=pframe)

Now the picture:

## png("SO_poly.png")
par(las=1,bty="l") ## cosmetic
plot(pressure~volume, data=dd, pch = 19, col = "firebrick",
     ylim=c(-100,500))

with(pframe, lines(volume, pressure, col="red"))

This doesn't look great, so I tried some other curve-fits.

Log-linear fit:

lm_fit2 <- lm(log(pressure) ~ poly(volume, 2, raw = TRUE),
             data=dd)
pframe$lpressure <- exp(predict(lm_fit2,newdata=pframe))
with(pframe, lines(volume, lpressure, col="purple"))

Exponential fit:

glm_fit <- glm(pressure ~ poly(volume,2),
               family=gaussian(link="log"),
               data=dd)
pframe$gpressure <- predict(glm_fit, newdata=pframe, type="response")
with(pframe, lines(volume, gpressure, col="blue"))
## dev.off()

enter image description here

You could also use ggplot2:

library(ggplot2)
ggplot(dd, aes(volume,pressure))+
    geom_point()+
    geom_smooth(method="lm",
                formula=y~poly(x,2))

Upvotes: 1

TechWizard
TechWizard

Reputation: 346

Use ggplot2: geom_smooth lm method

library(ggplot2)

df <- data.frame(pressure = c(400, 200, 100, 50, 25, 12.5, 6.25, 3.125),
                   volume = c(.25, .5, 1, 2, 4, 8, 16, 32))

# Fit a regression line. Change the method if you want the exponential fitting
ggplot(data = df, aes(x = pressure, y = volume)) +
  geom_point() +
  geom_smooth(method = "lm")

# If you just want to connect the dots
ggplot(data = df, aes(x = pressure, y = volume)) +
  geom_point() +
  geom_line()

enter image description here enter image description here

Upvotes: 1

Related Questions