library(ggplot2)
df <- data.frame(
Year = c(2015,2016,2017,2018,2019,2020),
Sales = c(200,120,350,270,400,150)
)
# plot scatter plot
ggscat <- df |>
ggplot()+aes(x = Year,y = Sales)+geom_point(size = 5,col = "blue")+
labs(title = "A Simple Scatter Plot Example",x = "Year",y = "Sales")
plotly::ggplotly(ggscat)Fitting A Scatter Plot
Hello! In this tutorial, we are going to learn how to fit a scatter plot using the ggplot2 package in the R programming language. So without too much talk, let’s dive into the R code.
A Simple Scatter Plot
In this example, we build a scatter plot, using the geom_point() function from the ggplot2 package, where we visualize the relationship between Year and Sales in the data frame, df. In the code, we plot Year on the X axis and Sales on the Y axis. Then, we wrap the graph object in plotly::ggplotly() to make the graph interactive.
We have now plotted a simple scatter plot visualizing the relationship between Year and Sales in the data frame, df. In the next example, we are going to demonstrate how to fit a scatter plot.
Fitting The Scatter Plot
Here, we add the geom_smooth() function to our code chunk to plot a red line that fits the dots to the regression line. In the function, we use the linear regression method to plot the line of best fit and color it red.
# plot fitted scatter plot
ggfit <- df |>
ggplot()+aes(x = Year,y = Sales)+geom_point(size = 5,col = "blue")+
geom_smooth(method = "lm",se = F,col = "red")+labs(title = "A Fitted Scatter Plot Example",x = "Year",y = "Sales")
plotly::ggplotly(ggfit)`geom_smooth()` using formula 'y ~ x'
The regression line helps us to evaluate the relationship between the independent variable on the X axis and the dependent variable on the Y axis. In our example, Sales fluctuates over the years, and so its relationship with Years is not linear. If it was, the dots would be very close to the regression line, indicating that sales increases as years also increase.
And that is how to fit a scatter plot, using the ggplot2 package in the R programming language.
If you enjoyed this tutorial, please visit Statistics Globe website, www.statisticsglobe.com for many more tutorials that will help you master the R programming language. Also, you can subscribe to their YouTube channel where you can watch their latest coding tutorials.