【问题标题】:Why is geom_smooth not plotting? (insufficient unique values error)为什么 geom_smooth 不绘图? (唯一值不足错误)
【发布时间】:2021-05-17 07:59:05
【问题描述】:

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

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

然后我使用 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). 

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

【问题讨论】:

标签: r ggplot2


【解决方案1】:

你可能需要类似的东西

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")用线连接组的手段...

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    • 2016-02-14
    • 2019-02-03
    • 2013-01-11
    • 2022-12-07
    • 2021-06-21
    相关资源
    最近更新 更多