我通常使用broom::augment()来创建.fitted.resid列,然后可以绘制这些列.意外地,我使用了非增强的模型对象,仍然得到了一个根据我的理解应该不起作用的图.ggplot2在哪里找到.resid.fitted

mod <- lm(Ozone ~ Solar.R + Wind + Temp, data = airquality)
mod$`.resid`
#> NULL
mod$`.fitted`
#> NULL
library(ggplot2)
ggplot(mod, aes(x = .fitted, y = .resid)) + geom_point()

创建于2024-02-01年第reprex v2.1.0

推荐答案

无论在ggPlot中传递什么,在完成绘制之前,首先将其传递到函数fortify中.下面来看一下ggploy函数:

ggplot2:::ggplot.default
function (data = NULL, mapping = aes(), ..., environment = parent.frame()) 
{
    if (!missing(mapping) && !inherits(mapping, "uneval")) {
        cli::cli_abort(c("{.arg mapping} should be created with {.fn aes}.", 
            x = "You've supplied a {.cls {class(mapping)[1]}} object"))
    }
    data <- fortify(data, ...)
    ....

该函数fortify是通用的,并且它确实包含用于线性模型对象的方法,其定义如下:

ggplot2:::fortify.lm
function (model, data = model$model, ...) 
{
    infl <- stats::influence(model, do.coef = FALSE)
    data$.hat <- infl$hat
    data$.sigma <- infl$sigma
    data$.cooksd <- stats::cooks.distance(model, infl)
    data$.fitted <- stats::predict(model)
    data$.resid <- stats::resid(model)
    data$.stdresid <- stats::rstandard(model, infl)
    data
}

请注意Fortify如何创建所有变量:

艾格

head(fortify(lm(Ozone ~ Solar.R + Wind + Temp, data = airquality)))
  Ozone Solar.R Wind Temp       .hat   .sigma      .cooksd   .fitted      .resid   .stdresid
1    41     190  7.4   67 0.04213526 21.26578 1.619281e-03 33.045483   7.9545175  0.38372526
2    36     118  8.0   72 0.02386496 21.28020 1.399323e-05 34.998710   1.0012902  0.04784798
3    12     149 12.6   74 0.01493584 21.24339 1.410343e-03 24.822814 -12.8228139 -0.60997176
4    18     313 11.5   62 0.07184509 21.28037 1.049577e-05 18.475226  -0.4752262 -0.02328889
7    23     299  8.6   65 0.06645355 21.26005 3.644684e-03 32.261431  -9.2614315 -0.45255232
8    19      99 13.8   59 0.04581198 21.12342 1.888167e-02 -6.949919  25.9499188  1.25423141

现在,这个数据集就是用于绘图的数据集.

R相关问答推荐

给定R中另一行中的值,如何插补缺失值

使用tidyverse / Mutate的存款账户余额

更改默认系列1以更改名称

如何得到R中唯一的组合群?

如何优化向量的以下条件赋值?

如何调整曲线图中的y轴标签?

合并DFS列表并将索引提取为新列

多个模拟序列间的一种预测回归关系

如何删除最后一个可操作对象

在使用bslb和bootstrap5时,有没有办法更改特定dt行的 colored颜色 ?

如何根据R中其他变量的类别汇总值?

在gggraph中显示来自不同数据帧的单个值

从线的交点创建面

按组跨多列创建伪变量

ggplot斜体轴刻度标签中的单个字符-以前的帖子建议不工作

如何使用grepl()在数据帧列表中 Select 特定字符串?

每行不同列上的行求和

Broom.Mixed::Augment不适用于Sample::分析

使用&Fill&Quot;在gglot中创建 colored颜色 渐变

真实世界坐标的逆st_变换