How to create Scatter plot with linear regression line of best fit in R | Data Analyst’s Recipe
Data Visualisation Recipe in R for Data Analysts and Beginners.
Scatter plots are a useful way to visualize the relationship between two variables, and linear regression lines can help identify trends in the data. In R, creating a scatter plot with a linear regression line of best fit is straightforward, especially with built-in datasets. In this tutorial, we will use the mtcars
dataset, which contains information on various car models.
Step 1: Load the mtcars
dataset
The first step is to load the mtcars
dataset into R. The mtcars
dataset is built into R, so there is no need to download any external files. You can simply load the dataset by typing data(mtcars)
in the console.
# Load the mtcars dataset
data(mtcars)
Step 2: Create a Scatter Plot
The next step is to create a scatter plot using the plot()
function. The plot()
function takes two arguments: the x-axis variable and the y-axis variable. In this case, we will use wt
(weight in thousands of pounds) as the x-axis variable and mpg
(miles per gallon) as the y-axis variable. We will also add axis labels and a title to the plot.