Extracting Regression coefficients from ggplot

Hello there,

I am relying on ggplot to create some scatterplots. Since ggplot does (for whatever reason) not seem to provide an easy way to get statistics of the plot, I use the script introduced here:

So my script looks like this:

ggplotRegression <- function (fit) {


ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
  geom_point() +
  stat_smooth(method = "lm", col = "red") +
  labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 5),
                     "Intercept =",signif(fit$coef[[1]],5 ),
                     " Slope =",signif(fit$coef[[2]], 5),
                     " P =",signif(summary(fit)$coef[2,4], 5)))
fit1 <- lm(Sepal.Length ~ Petal.Width, data = iris)

I now have the coefficient I want in the plot´s header ("Adj R2")... But I want to have it as a variable in my working space. My attempts to extract it out of the function above failed to far. Anyone knows a quick solution? (in optimal case not just for the "Adj R2", but for each of the statistics displayed in the header)


You are better off extracting the numbers into a dataframe before the ggplot() function.

broom is designed for this:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.