Create Several Curves to fit on data
Then we create linear regression models to the required degree and plot them on top of the scatter plot to see which one fits the data better. We use the lm() function to create a linear model. And then use lines() function to plot a line plot on top of scatter plot using these linear models.
Syntax:
lm( function, data)
where,
- function: determines the fitting polynomial function.
- data: determines the data frame over which function is to be fitted.
Example:
R
# create sample data sample_data <- data.frame (x=1:10, y= c (25, 22, 13, 10, 5, 9, 12, 16, 34, 44)) # fit polynomial regression models up to degree 5 linear_model1 <- lm (y~x, data=sample_data) linear_model2 <- lm (y~ poly (x,2,raw= TRUE ), data=sample_data) linear_model3 <- lm (y~ poly (x,3,raw= TRUE ), data=sample_data) linear_model4 <- lm (y~ poly (x,4,raw= TRUE ), data=sample_data) linear_model5 <- lm (y~ poly (x,5,raw= TRUE ), data=sample_data) # create a basic scatterplot plot (sample_data$x, sample_data$y) # define x-axis values x_axis <- seq (1, 10, length=10) # add curve of each model to plot lines (x_axis, predict (linear_model1, data.frame (x=x_axis)), col= 'green' ) lines (x_axis, predict (linear_model2, data.frame (x=x_axis)), col= 'red' ) lines (x_axis, predict (linear_model3, data.frame (x=x_axis)), col= 'purple' ) lines (x_axis, predict (linear_model4, data.frame (x=x_axis)), col= 'blue' ) lines (x_axis, predict (linear_model5, data.frame (x=x_axis)), col= 'orange' ) |
Output:
Curve Fitting in R
In this article, we will discuss how to fit a curve to a dataframe in the R Programming language.
Curve fitting is one of the basic functions of statistical analysis. It helps us in determining the trends and data and helps us in the prediction of unknown data based on a regression model/function.