Search code examples
rggplot2graphr-markdowngeom

How can fit a curve to my data using ggplot that doesn't necessarily go through every point?


I'm trying to fit a curve to my data points in R, but geom_smooth is just drawing an ugly line through all the points. I'm looking for a way to make a smooth curve that doesn't necessarily go through all the points.

This is my current graph

and here is the code I used to make it:

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

When I say fitted curve, I mean something like this


Solution

  • The "loess" method of smoothing a line in geom_smooth has a "span" argument which you can use for this purpose, e.g.

    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)
    

    Created on 2021-07-21 by the reprex package (v2.0.0)

    For more details see What does the span argument control in geom_smooth?