Get Fitted Values of Regression Line from ggplot2 Plot in R (Example Code)
In this tutorial you’ll learn how to get the line fit coordinates of a ggplot2 plot regression line in the R programming language.
Preparing the Example
data(iris) # Example data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
data(iris) # Example data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
install.packages("ggplot2") # Install ggplot2 package library("ggplot2") # Load ggplot2 package |
install.packages("ggplot2") # Install ggplot2 package library("ggplot2") # Load ggplot2 package
my_plot <- ggplot(iris, # ggplot2 graphic with regression line aes(x = Petal.Length, y = Petal.Width)) + geom_point() + stat_smooth() my_plot |
my_plot <- ggplot(iris, # ggplot2 graphic with regression line aes(x = Petal.Length, y = Petal.Width)) + geom_point() + stat_smooth() my_plot
Example: Apply ggplot_build() Function to Get Line Fit of ggplot2 Plot Object
my_plot_data <- ggplot_build(my_plot)$data[[2]][ , 1:2] # Extract coordinates of regression line head(my_plot_data) # x y # 1 1.000000 0.09901847 # 2 1.074684 0.12224953 # 3 1.149367 0.14558026 # 4 1.224051 0.16937599 # 5 1.298734 0.19400205 # 6 1.373418 0.21918890 |
my_plot_data <- ggplot_build(my_plot)$data[[2]][ , 1:2] # Extract coordinates of regression line head(my_plot_data) # x y # 1 1.000000 0.09901847 # 2 1.074684 0.12224953 # 3 1.149367 0.14558026 # 4 1.224051 0.16937599 # 5 1.298734 0.19400205 # 6 1.373418 0.21918890
Further Resources & Related Articles
You may find some further R programming tutorials in the following list.