Table of Contents
Introducing stat_regline_equation() for Enhanced Visualization
In the field of data science and statistical analysis, merely calculating metrics is often insufficient; effective visualization of relationships between variables is paramount for clear communication. Within the R programming environment, analysts overwhelmingly rely on the robust ggplot2 package to construct detailed scatterplots. A frequent and critical requirement is the ability to seamlessly integrate the mathematical equation of the fitted regression line directly onto this visual output. This integration provides crucial quantitative context, instantly transforming a standard plot into a comprehensive statistical summary that validates the observed graphical trend.
The task of displaying the precise equation of a fitted linear regression model is significantly simplified through specialized packages. The most efficient and recommended approach involves utilizing the powerful stat_regline_equation() function. This utility is a core component of the highly versatile ggpubr package, which is specifically engineered to help users generate graphics optimized for publication and professional reporting in R.
The primary value proposition of stat_regline_equation() lies in its automation. It calculates the necessary coefficients from the underlying statistical model, formats the resulting regression equation neatly, and positions it intelligently within the plot area. This capability drastically reduces the effort compared to manually extracting coefficients from a model summary and then annotating the plot using text functions. The following tutorial provides a thorough walkthrough, demonstrating how to integrate and deploy stat_regline_equation() effectively to produce high-quality, informative statistical graphics.
Prerequisites and Package Installation
Before we dive into the visualization steps, it is essential to ensure that your current R session is properly equipped with the necessary statistical and graphical libraries. Since the key functionality for automatically deriving and displaying the regression equation is not native to the base ggplot2 package, the dedicated ggpubr package must be installed and loaded first. Completing this preliminary step guarantees that the stat_regline_equation() function is recognized by the R interpreter and ready to execute when called.
If ggpubr is not already present on your system, you must run the installation command below in your R console. This process fetches the package from the CRAN (Comprehensive R Archive Network) and integrates it into your local library structure. It is important to remember that while installation is typically a one-time process per system, the package must be explicitly loaded into memory using the library() function every time you start a new R session where you plan to use its features.
install.packages('ggpubr')
Once the ggpubr package has been successfully installed, we can proceed to the next stage: preparing our sample data and fitting the statistical model we intend to visualize. When we reach the plotting stage, we will need to explicitly call the library() function for both ggplot2 and ggpubr to ensure that all necessary functions are immediately accessible for creating the combined graphic.
Preparing the Data and Fitting the Model
To effectively demonstrate the utility of stat_regline_equation(), we will start by simulating a simple dataset within R. This dataset, structured as a data frame, is designed to exhibit a clear and strong linear relationship, which is ideal for regression analysis. We define x as our predictor variable (independent variable) and y as our response variable (dependent variable), based on the hypothesis that changes in y are explained by changes in x. The careful construction of this data frame is the foundational step for all subsequent modeling and visualization.
The following R code snippet executes two critical actions: first, it creates the data frame named df using hard-coded values; second, it displays the contents of df in the console. Reviewing this output confirms the structure and ensures that the paired values for the predictor and response variables are correct before we proceed to the formal statistical modeling stage.
#create data frame
df <- data.frame(y=c(6, 7, 7, 9, 12, 13, 13, 15, 16, 19, 22, 23, 23, 25, 26),
x=c(1, 2, 2, 3, 4, 4, 5, 6, 6, 8, 9, 9, 11, 12, 12))
#view data frame
df
y x
1 6 1
2 7 2
3 7 2
4 9 3
5 12 4
6 13 4
7 13 5
8 15 6
9 16 6
10 19 8
11 22 9
12 23 9
13 23 11
14 25 12
15 26 12With the data frame established, our next logical step is to formally fit a simple linear regression model. We employ the standard R function, lm() (for linear model), designating x as the independent predictor variable and y as the dependent response variable. The lm() function performs the necessary calculations to find the line that minimizes the sum of squared residuals, effectively determining the “best-fit” line that represents the trend in the data points.
The comprehensive output generated by the summary(model) command is critical, offering detailed insights into the model’s performance, statistical significance (p-values), and variability. Most importantly for our visualization objective, it provides the exact numerical values for the intercept and the slope (coefficient for x). These coefficients form the precise algebraic backbone of the regression equation that stat_regline_equation() will subsequently display on the plot.
#fit linear regression model to data frame
model <- lm(y~x, data=df)
#view model summary
summary(model)
Call:
lm(formula = y ~ x, data = df)
Residuals:
Min 1Q Median 3Q Max
-1.4444 -0.8013 -0.2426 0.5978 2.2363
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 4.20041 0.56730 7.404 5.16e-06 ***
x 1.84036 0.07857 23.423 5.13e-12 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 1.091 on 13 degrees of freedom
Multiple R-squared: 0.9769, Adjusted R-squared: 0.9751
F-statistic: 548.7 on 1 and 13 DF, p-value: 5.13e-12Based on the numerical estimates for the intercept and the coefficient for x provided in the model summary, we can manually articulate the fitted regression equation. This formula encapsulates the mathematical relationship detected between the two variables and is exactly what the visualization function will automatically calculate and format for display:
- y = 4.20041 + 1.84036(x)
Basic Visualization with stat_regline_equation()
With the statistical model fitted, our immediate priority shifts to visualization. We must generate a scatterplot using the layers of ggplot2 to map the distribution of our raw data points (x versus y). Concurrently, we must introduce stat_regline_equation() to automatically compute and display the derived regression equation. This two-pronged approach instantly conveys both the visual distribution trend and the precise algebraic relationship, substantially enhancing the reader’s grasp of the statistical findings.
To begin, we must load the necessary libraries: ggplot2 and ggpubr. We then initiate the plot using the ggplot() function, setting the aesthetic mappings (aes(x, y)) to define which variables correspond to the axes. The data points are added using the geom_point() layer. Crucially, we then incorporate stat_regline_equation() as an additional layer. This function is designed to analyze the underlying data structure, perform the implicit linear regression fit, and neatly position the resulting equation on the graphic.
library(ggplot2)
library(ggpubr)
#create plot to visualize fitted linear regression model
ggplot(df, aes(x, y)) +
geom_point() +
stat_regline_equation()The execution of the code above generates our initial scatterplot. As intended, the stat_regline_equation() function correctly interprets the relationship between x and y, calculates the regression equation, and displays it prominently—by default, in the upper left corner of the plotting area. This immediate, automatic feedback confirms that the function is correctly implemented and aligned with the statistical assumptions of the data.
This produces the following plot:

Enhancing the Plot with the Regression Line
While displaying the algebraic equation is incredibly useful for statistical rigor, a complete visualization of a linear regression analysis requires drawing the actual fitted line that corresponds to that equation through the data points. This line serves as the graphical representation of the mathematical model, allowing viewers to immediately gauge the direction and magnitude of the relationship. To incorporate this visual element, we must add the geom_smooth() function, a feature within ggplot2 designed for adding smoothed conditional means or fitted regression lines.
When utilizing geom_smooth() alongside stat_regline_equation(), a specific and crucial argument must be supplied: setting method=’lm’ within the geom_smooth() call. This explicit instruction directs ggplot2 to fit a linear model (lm) to the data points. Failure to include this argument might lead geom_smooth() to default to a non-linear smoothing technique, such as LOESS (Locally Estimated Scatterplot Smoothing). If this occurred, the drawn line would not align with the equation calculated by stat_regline_equation(), resulting in a confusing and statistically misleading graphic.
By integrating geom_smooth(method=’lm’) into our existing plot syntax, we achieve a highly unified and informative visualization. This final graphic now includes the raw data, the statistically derived fitted line, the critical confidence interval (indicated by the shaded area), and the precise algebraic equation defining the line. This comprehensive approach maximizes both the clarity and the statistical integrity of the report.
library(ggplot2)
library(ggpubr)
#create plot to visualize fitted linear regression model
ggplot(df, aes(x, y)) +
geom_point() +
geom_smooth(method='lm') +
stat_regline_equation()This produces the following plot:

The resulting plot clearly showcases the linear regression line alongside the shaded area representing the model’s standard error and confidence interval. Critically, the fitted regression equation remains prominently displayed in the top left corner, ensuring perfect numerical synchronization with the visual line. This combined graphical and numerical output sets the standard for professional statistical reporting in R.
Additional Resources for R Visualization
Mastery of the advanced visualization techniques available through ggplot2 and complementary packages, such as ggpubr, is fundamental for effective data storytelling. The stat_regline_equation() function is just one example of the specialized utilities available to elevate your statistical graphics far beyond simple raw data plots.
We highly recommend that analysts seeking to deepen their expertise in data visualization and statistical modeling explore the extensive documentation and additional functions offered within both the ggplot2 and ggpubr libraries. Understanding how to customize visual elements, apply different plot themes, and integrate other crucial statistical metrics—such as the R-squared value—will significantly improve the quality and persuasive power of your analytical reports.
The following tutorials explain how to perform other common statistical and visualization tasks in the R environment:
<!–
Featured Posts
–>
Cite this article
Mohammed looti (2025). Learning Linear Regression Equations with `stat_regline_equation()` in R and ggplot2. PSYCHOLOGICAL STATISTICS. Retrieved from https://statistics.arabpsychology.com/use-stat_regline_equation-in-r/
Mohammed looti. "Learning Linear Regression Equations with `stat_regline_equation()` in R and ggplot2." PSYCHOLOGICAL STATISTICS, 13 Nov. 2025, https://statistics.arabpsychology.com/use-stat_regline_equation-in-r/.
Mohammed looti. "Learning Linear Regression Equations with `stat_regline_equation()` in R and ggplot2." PSYCHOLOGICAL STATISTICS, 2025. https://statistics.arabpsychology.com/use-stat_regline_equation-in-r/.
Mohammed looti (2025) 'Learning Linear Regression Equations with `stat_regline_equation()` in R and ggplot2', PSYCHOLOGICAL STATISTICS. Available at: https://statistics.arabpsychology.com/use-stat_regline_equation-in-r/.
[1] Mohammed looti, "Learning Linear Regression Equations with `stat_regline_equation()` in R and ggplot2," PSYCHOLOGICAL STATISTICS, vol. X, no. Y, ص Z-Z, November, 2025.
Mohammed looti. Learning Linear Regression Equations with `stat_regline_equation()` in R and ggplot2. PSYCHOLOGICAL STATISTICS. 2025;vol(issue):pages.