首页 > 解决方案 > 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

标签: rplotcurve

解决方案


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

在此处输入图像描述 在此处输入图像描述


推荐阅读