用置信区间绘制线性回归线

时间:2019-04-08 00:03:39

标签: r ggplot2 regression confidence-interval

我正试图绘制房屋的“平方英尺”如何影响相同房屋的“销售价格(1000美元)”。特别是,我希望从平方英尺(平方英尺)对销售价格的系数线绘制出来,并在该线周围假设灰色区域叠加原始数据点。

我尝试通过几种不同的方式来完成此操作。我尝试过的一种方法是使用来自library(jtools)的effect_plot函数。我使用了从https://cran.r-project.org/web/packages/jtools/vignettes/effect_plot.html中找到的编码。

但是当我运行此函数时,我没有得到图,只是得到一个错误:FUN(X [[i]],...)中的错误:找不到对象'Sales Price (in $1000)'

我尝试的第二种方法是通过手动创建一个新向量并尝试绘制置信区间。我的代码灵感来自Plotting a 95% confidence interval for a lm object

但是有了这个,我在conf_interval行中得到了一个错误:eval(predvars,data,env)中的错误:找不到对象“方脚”。我不知道如何纠正此错误。

最后,我尝试使用库(ggplot2)从https://rpubs.com/aaronsc32/regression-confidence-prediction-intervals得到启发来解决问题。

但是每次我运行R时,它都会创建一个坐标平面,该平面的中心只有一个点;没有线,没有实点,没有假设的置信区间。没有错误,我也无法弄清楚编码的问题。

library("jtools")
LRA1 <- lm(`Sales Price (in $1000)` ~ `Square feet` + Rooms +
 Bedrooms + Age,data=HomedataSRS) #LRA1 is the regression model
effect_plot(LRA1, pred = 'Square feet', inherit.aes = FALSE,
 plot.points = TRUE) #function should create graph
newSF = seq(min(HomedataSRS$`Square feet`),
            max(HomedataSRS$`Square feet`), by = 0.05)
conf_interval <- predict(LRA1, newdata=data.frame(x=newSF),
                 interval="confidence",level = 0.95)
plot(HomedataSRS$`Square feet`, HomedataSRS$`Sales Price (in $1000)`,
     xlab="Square feet", ylab="Sales Price(in $1000)",     
     main="Regression")
abline(LRA1, col="lightblue")
matlines(newSF, conf_interval[,2:3], col = "blue", lty=2)
library(ggplot2)
SFHT <- HomedataSRS %>% select(1:2) 
#This is to select the 2 variables I'm working with
ggplot(SFHT, aes(x='Square feet', inherit.aes = FALSE, 
       y='Sales Price (in $1000)')) +
       geom_point(color='#2980B9', size = 4) +
       geom_smooth(method=lm, color='#2C3E50')

数据: I take an n=35 random sample of this data with set.seed(1)

1 个答案:

答案 0 :(得分:1)

aes()

参数不应该引用。试试

ggplot(SFHT, aes(x = `Square feet`, y = `Sales Price (in $1000)`)) +
   geom_point(color='#2980B9', size = 4) +
   geom_smooth(method=lm, color='#2C3E50')

或者,您可以使用新的aes_string()函数:

ggplot(SFHT, aes_string(x='Square feet',y='Sales Price (in $1000)')) +
   geom_point(color='#2980B9', size = 4) +
   geom_smooth(method=lm, color='#2C3E50')

有关更多信息,请访问软件包站点:https://ggplot2.tidyverse.org/reference/aes_.html

相关问题