简体   繁体   English

将 1000 条回归线添加到 ggplot 的最佳方法是什么? (基于模型的引导)

[英]What is the best way to add 1000 regression lines to a ggplot? (Model-based bootstrapping)

From a bootstrapping model I have 1000 sets of coefficients for this regression model:从引导模型中,我有 1000 组系数用于此回归模型:

y = b0 + b1x + b2(x^2) y = b0 + b1x + b2(x^2)

What is the function call to plot a quadratic line if I already have the coefficients?如果我已经有了系数,绘制二次线的函数调用是什么 IE I do not want to "fit" a linear model to my data. IE 我不想为我的数据“拟合”线性模型。

I tried adding lines via a for loop to my ggplot object:我尝试通过 for 循环向我的 ggplot 对象添加行:

for (i in 1:1000) { 
  reg_line <- stat_function(fun=function(x) quad$coefficients[1] + 
                                      quad$coefficients[i,2]*x + quad$coefficients[i,3]*(x**2))
  reg_lines <- reg_lines + reg_line}

That didn't work - it seems to only add the last line in the loop.那没有用 - 它似乎只在循环中添加最后一行。

The reason I want to add 1000 regression lines to my plot is because it is for a homework problem - I am well aware this is not a common use case.我想在我的图中添加 1000 条回归线的原因是因为它是针对家庭作业的问题 - 我很清楚这不是一个常见的用例。

There may be other ways to do this, but hopefully this can give you some ideas.可能还有其他方法可以做到这一点,但希望这可以给你一些想法。 I used the mtcars dataset and generated some bootstrap samples for modelling.我使用了 mtcars 数据集并生成了一些用于建模的引导样本。 You can skip this step.您可以跳过此步骤。

library(ggplot2)
library(tidyr)
library(dplyr)

data(mtcars)

drat=seq(min(mtcars$drat), max(mtcars$drat), length.out=100)

# Bootstrap function
bs <- function() {
  df = mtcars[sample(1:nrow(mtcars), replace=TRUE),]
  lm_fit <- lm(mpg ~ drat+I(drat^2), data=df)
  data.frame(Model=predict(lm_fit, newdata=data.frame(drat))) # Replace with your own
}

foo <- replicate(10, bs()) # Simulate

You would start from here since you should already have a data frame or list of predicted values from your 1,000 bootstrap models.您将从这里开始,因为您应该已经拥有来自 1,000 个引导模型的数据框或预测值列表。 Reshape it into a very long form to create a grouping column for the geom_line function.将它改造成一个很长的形式,为geom_line函数创建一个分组列。


foo_long <- data.frame(foo, drat) %>%
  pivot_longer(cols=-drat, names_to="Model", values_to="mpg")

ggplot(data = mtcars, aes(x = drat, y = mpg)) + 
  geom_point(color='blue') +
  geom_line(data = foo_long, aes(x=drat, y=mpg, group=Model, color=Model)) +
  guides(color=FALSE)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM