0

Here is a reproducible example of my problem:

library(ggplot2)
library(dplyr)
library(ggpmisc)

df <- mtcars %>%
  filter(cyl==4)

ggplot(mtcars,aes(x=disp,y=hp))+
  geom_point() +
  stat_poly_line() + stat_poly_eq(use_label(c("eq")))

I want to be able to pull out the slope from regression equation that's plotted here on this ggplot chart. I have tried assigning the ggplot to a value of p and then checking the contents of p, but have not been able to find anything that looks quite like a regression equation.

Can someone help point me in the right direction? The end goal is to pull out the slope for each set of data when cyl = 4, 6, and 8. Then, I would place all of these #s in a dataframe that would look like the following:

Cyl Slope
4   0.339
6  -0.300
8   0.089
user2813606
  • 797
  • 2
  • 13
  • 37
  • 1
    If you just want the coefficients, you should fit your model using `lm`. Use `ggplot2` for plotting, not estimating coefficients. See https://stackoverflow.com/questions/37365724/ggplot2-how-to-get-values-for-the-regression-line-equation-r2-and-p-value for example – MrFlick Jun 08 '23 at 20:51
  • 1
    Well you use `mtcars` in your `ggplot` call, not `df`, So you can to compare the plot to `lm(hp~disp, data=mtcars)`. Those numbers will be the same (with different rounding maybe) – MrFlick Jun 08 '23 at 21:07
  • While [this article](https://www.roelpeters.be/how-to-add-a-regression-equation-and-r-squared-in-ggplot2/) starts out with using `lm`, it does provide insight into a lot of the tools created with `ggpubr `. I'm pretty confident you'll find what you're looking for (and what you didn't know you were looking for). – Kat Jun 08 '23 at 21:18

1 Answers1

2

You honestly don't need to pull the equations out of a plot. The plot calculates the coefficients internally using lm, so you can do the same in just a couple of lines:

do.call(rbind, lapply(c(4, 6, 8), function(x) {
  data.frame(Cyl = x,
             Slope = round(lm(hp ~ disp, mtcars[mtcars$cyl == x,])$coef[2], 3))
  })) |> 
  `row.names<-`(NULL)
#>   Cyl  Slope
#> 1   4  0.339
#> 2   6 -0.300
#> 3   8  0.089
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87