为什么我不能将曲线拟合到该图?

时间:2018-11-13 14:30:13

标签: r plot curve

我正在尝试为该图拟合曲线,但是遇到了麻烦。

代码:

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

结果:

Curve does not fit data

2 个答案:

答案 0 :(得分:1)

使用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

答案 1 :(得分:1)

您的主要问题是在回归模型中使用data$:您应该仅使用变量的名称。

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)

为了获得更平滑的曲线,我以更精确的volume值序列计算了预测值:

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

现在的图片:

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

这看起来不太好,所以我尝试了其他一些曲线拟合。

对数线性拟合:

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

指数拟合:

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

您也可以使用ggplot2

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