R语言 使用ggplot2创建残差图

zbq4xfa0  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(451)

我目前正在尝试将我的数据可视化,通过做残差分析来确定它是否正态分布。使用R中的内置功能来做残差图似乎很容易,但我更喜欢ggplot:)。我一直遇到找不到函数的问题,最近的是.fitted函数。
代码如下:

library(readxl)
library(ggplot2)

ggplot(Data_proj,
       aes(x = x1/1000,
           y = as.numeric(y))) +
      geom_point() +
      geom_smooth(method = "lm") +
      facet_wrap(~x2)

ggplot(Data_proj, aes(x = .fitted, .resid)) +
      geom_point() +
      geom_hline(yintercept = 0)

我得到的错误消息是:

Error in `geom_point()`:
    ! Problem while computing aesthetics.
    ℹ Error occurred in the 1st layer.
    Caused by error in `FUN()`:
    ! object '.fitted' not found
    Run `rlang::last_trace()` to see where the error occurred.

有人知道我可能做错了什么吗?谢谢,祝你有美好的一天!
编辑:我的数据看起来像这样:

dput(head(Data_proj)):
structure(list(x1 = c(8135, 1629, 2824, 9780, 8856, 10387), x2 = c(1, 
1, 1, 0, 1, 1), y = c("92.1281", "52.3726", "49.3202", "195.8212", 
"100.8019", "113.7111"), .fitted = c(`1` = 128.689193244635, 
`2` = 45.2529218882561, `3` = 60.5782130457833, `4` = 149.785514545164, 
`5` = 137.935665984866, `6` = 157.569992982502), .resid = c(`1` = -36.5610932446345, 
`2` = 7.11967811174389, `3` = -11.2580130457833, `4` = 46.0356854548364, 
`5` = -37.1337659848664, `6` = -43.8588929825017)), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))
0lvr5msh

0lvr5msh1#

您未指定数据和模型:试试这个:

library(dplyr)
library(ggplot2)

lm(mpg ~ disp, data = mtcars) %>% 
  ggplot(aes(.fitted, .resid)) +
  geom_point() +
  geom_hline(yintercept = 0)+
  labs(title='Residual vs. Fitted Values Plot', x='Fitted Values', y='Residuals')

相关问题