使用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
相关产品推荐
相关产品推荐

