Skip to content
Related Articles

Related Articles

Improve Article

Fit Smooth Curve to Plot of Data in R

  • Last Updated : 16 May, 2021
Geek Week

In this article, we will learn about the concept to fit a smooth curve to the plot of data in R Programming. Smoothing is an important concept in data analysis. It is also known n as curve fitting and low pass filtering. The most common non-parametric method used for smoothing is loess() function. Loess is an abbreviation for Local Regression used to fit multiple regressions in the local neighborhoods. The span argument is used to control the size of the neighborhood. The size ranges between 0 and 1. The greater is the span value, the more smooth will be the fitted curve.

Use of Loess() function: Loess() function is used on a numerical vector to smoothen it. It is also used to predict the Y locally.

Syntax: loess(y ~ x)

Return: It smooth curve to plot of data 

Example 1: Below is an implementation to fit a smooth curve to a plot:


# Create example data
x <- 1:80
y <- sort(rnorm(80))
# Apply loess function
values <- loess(y ~ x)    
plot(x, y)                      
      col = "blue",
      lwd = 2)


In the above example loess() function is used to fit a smooth curve into plot. The lwd parameter is used to specify the line type of the smooth curve. The arguments x and y are used to provide coordination to the plot. The loess function will then set a smooth curve in the plot.

Example 2: Another example is illustrated using loess() function:


x <- c(7  ,5,  2,  9,  1,  9,  17,  8,  9, 10)
y <- c(12, 14, 16, 18, 20, 2,  4,  6,  8,  7 )
values <- loess(y ~ x)
plot(x, y)
lines(predict(values), col = 'red', lwd = 2)


In the above example, X and Y axis values are plotted. The smooth curve is fitted using the loess function. The prediction will be an array of the appropriate dimensions in a smooth fitted curve.

My Personal Notes arrow_drop_up
Recommended Articles
Page :