r - 为什么 geom_smooth 不绘图? (唯一值不足错误)

我正在尝试比较水手队和白袜队之间的历史每日上座率。

我使用 MySQL 数据库创建了我的数据框,并将其缩减为以下列:datehometeamdayofweek 和 attendance。

然后我使用 lubridate 将编码日期的数字转换为 R 中的 Date 字段。我还将比赛的出勤率报告 0 设置为 NA。我都做了:

sea_attendance <- sea_attendance %>%
  mutate(the_date = ymd(date),
         attendance = ifelse(attendance == 0, NA, attendance))

我试着用这个来绘制它:

ggplot(sea_attendance,
       aes(x = wday(the_date), y = attendance,
           color = hometeam)) +
  geom_jitter(height = 0, width = 0.2, alpha = 0.2) +
  geom_smooth() +
  scale_y_continuous("Attendance") +
  scale_x_continuous("Day of the Week", breaks = 1:7,
                    labels = wday(1:7, label = TRUE)) +
  scale_color_manual(values = c("blue", "grey"))

结果很酷,但我无法让 geom_smooth 工作:

我遇到了这个错误:

`geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
Warning messages:
1: Removed 44 rows containing non-finite values (stat_smooth). 
2: Computation failed in `stat_smooth()`:
x has insufficient unique values to support 10 knots: reduce k. 
3: Removed 44 rows containing missing values (geom_point). 

这是教科书上的一道题。我已经盯着它看了一个小时,试图弄清楚哪里出了问题。

最佳答案

你可能需要类似的东西

geom_smooth(method="gam", formula = y ~ s(x, bs = "cs", k=5))

ggplot2(调用 mgcv 包)试图通过 7 个唯一的 x 值(抖动之前)和默认的“节”数计算平滑曲线(样条断点)设置为 10。

您还可以使用替代的 geom_smooth() 方法(例如 method="loess"method="lm"(尽管后者会给你一个线性拟合;你可以用例如 formula = y ~ poly(x,3)) 或使用 stat_summary(fun.y=mean, geom="line") 用一条线连接各组的方法 ...

相关帖子(有用,但不一定回答清楚):

  • R : stat_smooth error cause by sufficient unique values
  • R : stat_smooth groups (x axis)
  • Passing arguments to ggplot and facet_grid

https://stackoverflow.com/questions/67562178/

相关文章:

sql - 如何计算运行平均值

haskell - 在 haskell 中给 `_` 一个类型签名

c++ - char a[n][m] 和 char a[][m] 有区别吗?

python - 检查是否存在与列表中的字符串匹配的子字符串

amazon-web-services - 为什么 X-Forwarded-Proto 在 Elas

kubernetes - 如何将 kubernetes 的一个 secret 值复制到同一 name

visual-studio-code - 代码行数旁边的竖线是什么

java - 如果读取字节数为 0,是否有任何理由继续读取 InputStream?

node.js - 如何使用 NestJS 为多个国家/地区编写调度程序 12 :00AM(will

python - 如何减少 PyQt5 QGridLayout 中两个小部件之间的空间?