首页 > 解决方案 > 如何使用不一定经过每个点的 ggplot 将曲线拟合到我的数据中?

问题描述

我正在尝试将曲线拟合到 R 中的数据点,但 geom_smooth 只是在所有点上画了一条丑陋的线。我正在寻找一种方法来制作不一定经过所有点的平滑曲线。

这是我目前的图表

这是我用来制作它的代码:

data <- data.frame(thickness = c(0.25, 0.50, 0.75, 1.00),
               capacitance = c(1.844, 0.892, 0.586, 0.422))

ggplot(data, aes(x = thickness, y = capacitance)) + 
geom_point() + 
geom_smooth(method = "loess", se = F, formula = (y ~ (1/x)))

当我说拟合曲线时,我的意思是这

标签: rggplot2graphr-markdowngeom

解决方案


在 geom_smooth 中平滑线的“黄土”方法有一个“跨度”参数,您可以使用它来实现此目的,例如

library(tidyverse)
data <- data.frame(thickness = c(0.25, 0.50, 0.75, 1.00),
                   capacitance = c(1.844, 0.892, 0.586, 0.422))

ggplot(data, aes(x = thickness, y = capacitance)) + 
  geom_point() + 
  geom_smooth(method = "loess", se = F,
              formula = (y ~ (1/x)), span = 2)

reprex 包于 2021-07-21 创建 (v2.0.0 )

有关更多详细信息,请参阅geom_smooth 中的 span 参数控制什么?


推荐阅读