为什么 ggpairs 函数中的散点图上面没有黄土层?

Why scatter plots in ggpairs function don't have the loess layer on them?

我有一个快速的问题,但无法弄清楚问题出在哪里。我想绘制一个我拥有的数据集,并在这里找到了一个解决方案:

但是,我似乎无法弄清楚我的方法有什么问题。下面是带有简单 mtcars 数据集的代码块:

library(ggplot2)
library(GGally)


View(mtcars)

GGally::ggpairs(mtcars,
                 lower= list(
                   ggplot(mapping = aes(rownames(mtcars))) + 
                     geom_point()+
                     geom_smooth(method = "loess"))
                )

如您所见,这是我的输出,它没有将平滑层放在散点图上。我想用它来对我的实际数据集进行回归分析。任何方向或解释都会很好。谢谢!

来自@Edward 评论的 post 中的解决方案在这里适用于 mtcars。下面的代码片段复制了上面的情节,添加了黄土线:

library(ggplot2)
library(GGally)

View(mtcars)

# make a function to plot generic data with points and a loess line
my_fn <- function(data, mapping, method="loess", ...){
  p <- ggplot(data = data, mapping = mapping) + 
    geom_point() + 
    geom_smooth(method=method, ...)
  p
}

# call ggpairs, using mtcars as data, and plotting continuous variables using my_fn    
ggpairs(mtcars, lower = list(continuous = my_fn))

在你的代码片段中,第二个参数 lower 有一个 ggplot 对象传递给它,但它需要的是一个 list 具有特定命名的元素,指定要做什么具有特定的变量类型。列表中的元素可以是函数或字符向量(但不能是 ggplot 对象)。来自 ggpairs 文档:

upper and lower are lists that may contain the variables 'continuous', 'combo', 'discrete', and 'na'. Each element of the list may be a function or a string. If a string is supplied, it must implement one of the following options:

continuous exactly one of ('points', 'smooth', 'smooth_loess', 'density', 'cor', 'blank'). This option is used for continuous X and Y data.

combo exactly one of ('box', 'box_no_facet', 'dot', 'dot_no_facet', 'facethist', 'facetdensity', 'denstrip', 'blank'). This option is used for either continuous X and categorical Y data or categorical X and continuous Y data.

discrete exactly one of ('facetbar', 'ratio', 'blank'). This option is used for categorical X and Y data.

na exactly one of ('na', 'blank'). This option is used when all X data is NA, all Y data is NA, or either all X or Y data is NA.

我的代码片段起作用的原因是因为我将 list 传递给 lower,其中包含一个名为 'continuous' 的元素,即 my_fn(生成 ggplot).