R 计算在 `stat_smooth()` 中失败:# x 没有足够的唯一值来支持 10 节:减少 k

use*_*904 4 r ggplot2

我正在跟踪https://drsimonj.svbtle.com/plot-some-variables-against-many-others中的最后一组代码,并修改了我的数据的代码。

在此代码中:

  t3 %>%
  gather(-Border, key = "var", value = "value") %>%
  ggplot(aes(x = value, y = Border)) +
  geom_point() +
  stat_smooth() +
  facet_wrap(~ var, scales = "free") +
  theme_bw() 
Run Code Online (Sandbox Code Playgroud)

我收到此错误消息:计算失败stat_smooth():x 没有足够的唯一值来支持 10 节:减少 k。

该代码无需 stat_smooth() 命令即可运行,但我需要平滑的线条。

除了一个具有 20 个值的 var 之外,其他所有 var 都有 5 到 6 个唯一值。如何减少 k?ak为5合理吗?样本量为 1,000。

谢谢

All*_*ron 7

显然,我们没有您的数据,但我们可以生成一些数据来重现您的问题:

library(ggplot2)

set.seed(1)

df <- data.frame(x = rep(1:10, 150), y = rnorm(1500), 
                 group = c(rep("A", 1490), rep("B", 10)))[-1500,]

ggplot(df, aes(x, y, color = group)) + stat_smooth()
#> `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
#> Warning: Computation failed in `stat_smooth()`
#> Caused by error in `smooth.construct.cr.smooth.spec()`:
#> ! x has insufficient unique values to support 10 knots: reduce k.
Run Code Online (Sandbox Code Playgroud)

出现此错误的原因是,如果您的任何组拥有超过 1,000 个数据点,则默认情况下将在所有stat_smooth组上使用广义相加模型。来自文档:

平滑方法是根据method = NULL最大组(跨所有面板)的大小来选择的。stats::loess()用于少于 1,000 个观测值;否则mgcv::gam()与使用formula = y ~ s(x, bs = "cs")

这意味着,如果一个或多个组非常小,stat_smooth最终将gam使用这些默认设置运行回归,由于指定模型的点数不足,回归将失败。

我们可以通过指定method = "loess"来解决这个问题stat_smooth

ggplot(df, aes(x, y, color = group)) + stat_smooth(method = "loess")
#> `geom_smooth()` using formula = 'y ~ x'
Run Code Online (Sandbox Code Playgroud)

创建于 2022 年 11 月 14 日,使用reprex v2.0.2