英文:
Pull out Regression Eqn from ggplot
问题
这是一个可以重现我的问题的示例:
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")))
我想要能够提取绘制在这个ggplot图上的回归方程的斜率。我尝试将ggplot分配给变量p,然后检查p的内容,但没有找到看起来像回归方程的内容。
有人可以帮助我指明正确的方向吗?最终目标是提取当cyl = 4、6和8时每组数据的斜率。然后,我会将所有这些数字放入一个数据框中,看起来像下面这样:
Cyl Slope
4 0.339
6 -0.300
8 0.089
英文:
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
答案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
计算系数,因此您可以在几行代码中完成相同的操作:"
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
请注意,我只提供了代码部分的翻译,不包括问题中的其他内容。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论