【问题标题】:Why can't I fit a curve to this plot?为什么我不能在这个图上拟合曲线?
【发布时间】:2018-11-13 14:30:12
【问题描述】:

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

代码:

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

结果:

【问题讨论】:

  • data$volumepredict(...) 是否按照您想要的方式排序?
  • 是的,它们已订购。

标签: r plot curve


【解决方案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()

【讨论】:

    【解决方案2】:

    您的主要问题是在回归模型中使用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()
    

    你也可以使用ggplot2:

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

    【讨论】:

      猜你喜欢
      • 2014-12-05
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-10
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      相关资源
      最近更新 更多