从 ggplot 中提取回归方程。

huangapple go评论91阅读模式
英文:

Pull out Regression Eqn from ggplot

问题

这是一个可以重现我的问题的示例:

  1. library(ggplot2)
  2. library(dplyr)
  3. library(ggpmisc)
  4. df <- mtcars %>%
  5. filter(cyl==4)
  6. ggplot(mtcars, aes(x=disp, y=hp)) +
  7. geom_point() +
  8. stat_poly_line() + stat_poly_eq(use_label(c("eq")))

我想要能够提取绘制在这个ggplot图上的回归方程的斜率。我尝试将ggplot分配给变量p,然后检查p的内容,但没有找到看起来像回归方程的内容。

有人可以帮助我指明正确的方向吗?最终目标是提取当cyl = 4、6和8时每组数据的斜率。然后,我会将所有这些数字放入一个数据框中,看起来像下面这样:

  1. Cyl Slope
  2. 4 0.339
  3. 6 -0.300
  4. 8 0.089
英文:

Here is a reproducible example of my problem:

  1. library(ggplot2)
  2. library(dplyr)
  3. library(ggpmisc)
  4. df &lt;- mtcars %&gt;%
  5. filter(cyl==4)
  6. ggplot(mtcars,aes(x=disp,y=hp))+
  7. geom_point() +
  8. stat_poly_line() + stat_poly_eq(use_label(c(&quot;eq&quot;)))

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:

  1. Cyl Slope
  2. 4 0.339
  3. 6 -0.300
  4. 8 0.089

答案1

得分: 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:"
"你实际上不需要从图中提取方程式。图表内部使用lm计算系数,因此您可以在几行代码中完成相同的操作:"

  1. do.call(rbind, lapply(c(4, 6, 8), function(x) {
  2. data.frame(Cyl = x,
  3. Slope = round(lm(hp ~ disp, mtcars[mtcars$cyl == x,])$coef[2], 3))
  4. })) |&gt;
  5. `row.names&lt;-`(NULL)
  6. #&gt; Cyl Slope
  7. #&gt; 1 4 0.339
  8. #&gt; 2 6 -0.300
  9. #&gt; 3 8 0.089

请注意,我只提供了代码部分的翻译,不包括问题中的其他内容。

英文:

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:

  1. do.call(rbind, lapply(c(4, 6, 8), function(x) {
  2. data.frame(Cyl = x,
  3. Slope = round(lm(hp ~ disp, mtcars[mtcars$cyl == x,])$coef[2], 3))
  4. })) |&gt;
  5. `row.names&lt;-`(NULL)
  6. #&gt; Cyl Slope
  7. #&gt; 1 4 0.339
  8. #&gt; 2 6 -0.300
  9. #&gt; 3 8 0.089

huangapple
  • 本文由 发表于 2023年6月9日 04:40:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76435548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定