You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ggplot重现折线图时生成Race分类变量失败如何解决?

问题分析与修正方案
  • 你的代码第一个问题出在case_when的判断条件中使用了&&运算符:&&是标量逻辑与,仅返回单个逻辑值,无法对数据集逐行判断,需要替换为支持逐行运算的矢量化&运算符。
  • 第二个问题是不需要对数据按type和shortcut分组,直接在全量数据集上执行mutate即可生成race分类变量。

修正后完整代码

# 生成race分类变量
newdata <- records %>%
  mutate(race = case_when( 
    type == "Three lap" & shortcut == "No" ~ "Three lap with no shortcut",
    type == "Three lap" & shortcut == "Yes" ~ "Three lap with shortcut",
    type == "Single lap" & shortcut == "No" ~ "Single lap with no shortcut",
    type == "Single lap" & shortcut == "Yes" ~ "Single lap with shortcut"
  )) 

# 绘制目标可视化图
ggplot(data = newdata, mapping = aes(x = date, y = time, color = race)) +
  geom_line() + 
  geom_point()

如果需要调整图例的展示顺序,可以手动指定race的因子水平:

newdata$race <- factor(newdata$race, 
                       levels = c("Three lap with no shortcut", 
                                  "Three lap with shortcut",
                                  "Single lap with no shortcut",
                                  "Single lap with shortcut"))

内容的提问来源于stack exchange,提问作者Thuy Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 22:30:05