我正在尝试比较水手队和白袜队之间的历史每日上座率数据。
我使用 MySQL 数据库创建了数据框架,并将其缩减为以下几列:date、hometeam、dayofweek和出勤率。
然后,我将lubridate编码日期的数字转换为DateR 中的字段。我还将报告 0 的比赛出席人数设置为 NA。我都做了:
sea_attendance <- sea_attendance %>%
mutate(the_date = ymd(date),
attendance = ifelse(attendance == 0, NA, attendance))
Run Code Online (Sandbox Code Playgroud)
我试图用这个来绘制它:
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"))
Run Code Online (Sandbox Code Playgroud)
结果很酷,但我无法开始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).
Run Code Online (Sandbox Code Playgroud)
这是教科书上的问题。我已经盯着它看了一个小时,试图找出我哪里出了问题。
你可能需要类似的东西
geom_smooth(method="gam", formula = y ~ s(x, bs = "cs", k=5))
Run Code Online (Sandbox Code Playgroud)
ggplot2(调用该mgcv包)尝试通过 7 个唯一的 x 值(抖动之前)计算一条平滑曲线,默认的“结”数(样条线断点)设置为 10。
您还可以使用替代geom_smooth()方法(例如method="loess"或method="lm"(尽管后者将为您提供线性拟合;您可以使用例如将其设为多项式formula = y ~ poly(x,3)),或者使用stat_summary(fun.y=mean, geom="line")线连接组的平均值...
相关帖子(有用,但不一定回答清楚):