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

标签 r ggplot2

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

我使用 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 工作:

jittered plot of attendance by week

我遇到了这个错误:

`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 - 为什么 geom_smooth 不绘图? (唯一值不足错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67562178/

相关文章:

r - 使用 R 和 ggplot2 时连续缩放的错误

r - R 中的 Lebesgue-Stieltjes 集成

删除无边的自环和顶点

r - `<<-` 的 R 帮助文件实际上是否正确?

r - 查找向量行中的部分文本 +[r]

r - 如何使用ggplot2在轴标签上显示层次结构?

r - 使用ggplot2仅将一个分割添加到一个构面

r - 将图像插入到 ggplot 中的条形图中

r - 使用 24 小时制数据创建圆形图的方法是什么?

删除包含零的行