Add regression equation to plot in R

How to add a Regression Equation to a Plot in R


Introduction to Visualizing Regression Models in R

When conducting data analysis, visualizing the relationship between variables is paramount. A common requirement, especially in statistical reporting or academic publications, is to display the calculated regression equation directly onto a scatter plot. This practice significantly enhances the interpretability of the model, allowing observers to immediately grasp the mathematical relationship derived from the data. The goal of this tutorial is to produce a clear, publication-quality visualization similar to the example shown below, which presents both the raw data points and the derived linear model summary.

The visualization process in R, the industry-standard statistical programming language, has been revolutionized by powerful package ecosystems. While basic plotting functions exist, creating high-quality graphics that seamlessly integrate statistical results often requires advanced tools. This tutorial focuses specifically on achieving this integration—displaying the regression line and its corresponding mathematical formula—using highly efficient and user-friendly R libraries, transforming raw data into meaningful graphical summaries.

Achieving this professional visual output is straightforward when utilizing specialized packages. Specifically, we will leverage the capabilities of ggplot2, which forms the foundation for declarative graphics in R, and the complementary package, ggpubr. The ggpubr package provides dedicated functions designed to automatically calculate and annotate key statistical results, such as the regression equation, directly onto a ggplot2 object, thereby streamlining the annotation process significantly.

Add regression equation to plot in R

Prerequisites: Essential R Packages

Before diving into the coding steps, it is essential to ensure that the necessary statistical and graphical libraries are installed and loaded into your R environment. The workflow relies entirely on two powerful packages: ggplot2 and ggpubr. If these packages are not yet installed, you must first run install.packages("ggplot2") and install.packages("ggpubr") in your R console before proceeding to the code execution phase outlined in the subsequent steps.

The ggplot2 package is the backbone of modern data visualization in R, built upon the principles of the Grammar of Graphics. It allows users to construct complex plots layer by layer, offering exceptional flexibility and control over aesthetic mappings and geometric representations. For this specific task, ggplot2 provides the fundamental functions like ggplot(), geom_point(), and geom_smooth(), which are crucial for defining the initial scatterplot and fitting the linear regression line.

The supplementary package, ggpubr, simplifies the arduous process of creating publication-ready plots. While ggplot2 is highly versatile, adding complex statistical annotations often requires manually extracting model results and formatting them using text functions. ggpubr streamlines this through functions such as stat_regline_equation and stat_cor, which automatically calculate and display the regression formula and correlation statistics, respectively, minimizing manual effort and potential transcription errors.

Step 1: Preparing and Understanding the Sample Data

To provide a clear, reproducible illustration of the process, we begin by generating a synthetic dataset. This step involves creating two related variables, ‘x’ (the independent variable) and ‘y’ (the dependent variable), where ‘y’ is defined as a simple linear function of ‘x’ plus a degree of random noise, accurately simulating observational data where relationships are not perfectly deterministic.

We initiate the example by using the set.seed(1) function. Setting the seed is critically important for ensuring reproducibility, guaranteeing that the sequence of random numbers generated (specifically, the noise component added to Y) remains identical every time the code block is executed. Following this initialization, we create a data frame, df, containing 100 observations for the independent variable ‘x’, ranging sequentially from 1 to 100.

The dependent variable ‘y’ is constructed based on a baseline linear model: y = 4*df$x + noise. The noise term is generated using rnorm(100, sd=20), which creates 100 random values drawn from a normal distribution with a specified standard deviation (sd) of 20. This intentional introduction of variability ensures the resulting data exhibits a clear, yet imperfect, linear relationship, closely mimicking real-world data complexity. The final step involves inspecting the beginning of the resulting data frame using the head(df) function to confirm its structure and variable values prior to visualization.

#make this example reproducible
set.seed(1)

#create data frame
df <- data.frame(x = c(1:100))
df$y <- 4*df$x + rnorm(100, sd=20)

#view head of data frame
head(df)

  x         y
1 1 -8.529076
2 2 11.672866
3 3 -4.712572
4 4 47.905616
5 5 26.590155
6 6  7.590632

Step 2: Constructing the Base Scatterplot and Regression Line

With the data successfully prepared and loaded, the next phase involves generating the core visualization using the declarative syntax of ggplot2. This process requires explicitly loading both the graphics and annotation libraries and defining the initial plot structure, which includes mapping the aesthetic variables (x and y) and selecting the appropriate geometric layers to display the raw data and the fitted model.

Before defining the plot itself, we must load both ggplot2 and ggpubr using the library() function to make their respective functions available for use. The primary plotting syntax begins with ggplot(data=df, aes(x=x, y=y)), which serves two critical purposes: it specifies the data source (df) and defines the required aesthetic mapping (aes), indicating which variables correspond to the horizontal and vertical axes.

The plot is then built by adding geometric layers. geom_point() is included first to render the visual representation of the raw data points onto the graph. Subsequently, we add the geom_smooth(method="lm") layer. The geom_smooth layer calculates and draws a smoothed relationship, and by setting method="lm" (signifying Linear Regression), it instructs ggplot2 to specifically fit and visualize the Ordinary Least Squares regression line, typically accompanied by a shaded confidence interval band (the default setting).

#load necessary libraries
library(ggplot2)
library(ggpubr)

#create plot with regression line and regression equation
ggplot(data=df, aes(x=x, y=y)) +
        geom_smooth(method="lm") +
        geom_point() +
        stat_regline_equation(label.x=30, label.y=310)

Step 3: Integrating the Regression Equation (stat_regline_equation)

The defining feature of this approach is the integration of the stat_regline_equation() function, a specialized tool provided by the ggpubr package. This function automatically executes the underlying linear regression calculation using the variables mapped in the plot’s aesthetics, extracts the intercept and slope coefficients, and then dynamically constructs the full mathematical formula as a text string.

This automated annotation is highly efficient, eliminating the need for manual calculation or string manipulation. It results in a clearly displayed equation that summarizes the fitted relationship. Based on the coefficients derived from our synthetic data, the fitted regression equation is determined to be: y = 2.6 + 4*(x). This result confirms that the model accurately recovered the primary structure of our data generation process (which used a slope of 4).

The final component of this step is specifying the display coordinates using the label.x and label.y parameters. These parameters are crucial because they dictate the exact (x, y) coordinates on the plot where the regression formula string will be positioned. For optimal clarity, these coordinates (set here to x=30 and y=310) must be chosen carefully to ensure the text is visible, does not obscure essential data points, and is situated within a suitable blank area of the plotting region.

Add regression equation to plot in R

Step 4: Enhancing the Visualization with R-Squared (stat_cor)

While the regression equation defines the mathematical line, it does not quantify the goodness-of-fit—that is, how well the model accounts for the total variance observed in the dependent variable. For a complete statistical summary, it is standard practice to include the R-squared (R²) value. The ggpubr package addresses this need through the stat_cor() function.

The stat_cor() function is designed to calculate and display various correlation statistics. To specifically request the R-squared value for the linear model, we must use the aesthetic mapping aes(label=..rr.label..). The ..rr.label.. is a predefined internal placeholder within ggpubr that represents the coefficient of determination (R²), formatted correctly for graphical output.

When adding this second line of statistical text, careful attention must be paid to its vertical offset. We reuse the identical horizontal placement (label.x=30) as the regression formula for alignment, but we decrease the vertical coordinate (label.y=290) to ensure the R-squared value appears directly below the regression formula without any overlap. The simultaneous use of stat_regline_equation and stat_cor provides a comprehensive, two-line statistical summary embedded directly within the visualization.

#load necessary libraries
library(ggplot2)
library(ggpubr)

#create plot with regression line, regression equation, and R-squared
ggplot(data=df, aes(x=x, y=y)) +
        geom_smooth(method="lm") +
        geom_point() +
        stat_regline_equation(label.x=30, label.y=310) +
        stat_cor(aes(label=..rr.label..), label.x=30, label.y=290)

Interpreting the Complete Regression Output

The final plot, generated by executing the code in Step 4, successfully integrates all essential components for a rigorous visual analysis of a linear regression model. We now have the raw data distribution, the line of best fit calculated via the Ordinary Least Squares (OLS) method, and the definitive descriptive statistical annotations printed clearly on the graph.

Regression line with equation and R-squared value in ggplot2

Upon reviewing the visualization, we extract two primary pieces of quantitative information. First, the regression equation (e.g., y = 2.6 + 4.0x) defines the relationship, indicating the precise intercept and the marginal effect of X on Y (the slope). Second, the R-squared value, calculated for this specific model, is approximately 0.98.

This high R-squared value is critical for model assessment. It means that 98% of the variability observed in the dependent variable (Y) is statistically explained by the independent variable (X) through the fitted linear model. Such a high value indicates an extremely strong fit between the data and the model, confirming that the simulated relationship was successfully captured by the lm function, even with the added noise component.

Conclusion and Further Resources

Mastering the visualization of statistical models is a core competency for any professional engaging in data analysis or quantitative research. By effectively combining the flexible graphical engine of ggplot2 with the sophisticated statistical annotation capabilities provided by ggpubr, R users can efficiently generate plots that are both visually appealing and statistically sound. The capability to automatically integrate the regression equation and the R-squared value directly onto the graph significantly enhances reporting accuracy and streamlines the overall data workflow.

We have successfully demonstrated the synergistic use of geom_smooth(method="lm"), stat_regline_equation(), and stat_cor() to produce a comprehensive graphical summary. Consistent application of these techniques, alongside careful attention to positioning parameters like label.x and label.y, will ensure that your statistical visualizations meet the highest standards of clarity and professional presentation.


You can find more detailed R tutorials, covering a wide array of topics from advanced statistical modeling to specialized visualization techniques, on relevant data science educational platforms dedicated to expanding quantitative skills.

Cite this article

stats writer (2025). How to add a Regression Equation to a Plot in R. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-to-add-a-regression-equation-to-a-plot-in-r/

stats writer. "How to add a Regression Equation to a Plot in R." PSYCHOLOGICAL SCALES, 9 Dec. 2025, https://scales.arabpsychology.com/stats/how-to-add-a-regression-equation-to-a-plot-in-r/.

stats writer. "How to add a Regression Equation to a Plot in R." PSYCHOLOGICAL SCALES, 2025. https://scales.arabpsychology.com/stats/how-to-add-a-regression-equation-to-a-plot-in-r/.

stats writer (2025) 'How to add a Regression Equation to a Plot in R', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-to-add-a-regression-equation-to-a-plot-in-r/.

[1] stats writer, "How to add a Regression Equation to a Plot in R," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, December, 2025.

stats writer. How to add a Regression Equation to a Plot in R. PSYCHOLOGICAL SCALES. 2025;vol(issue):pages.

Download Post (.PDF)
Slide Up
x
PDF
Scroll to Top