R脚本中Plotly正常运行,RMarkdown调用source时分面变量报错
问题分析与解决方案
报错“At least one layer must contain all faceting variables, Name”的核心原因是:你的ggplot分面使用了Name变量,但图层(如geom_col)未包含该变量,ggplotly转换时无法找到分面所需变量;同时脚本运行环境与RMarkdown渲染环境的变量作用域差异,也可能导致单独运行正常但渲染报错。
以下是几种可行的解决方法:
方法1:在ggplot美学映射中加入分面变量
修改R脚本中的rpe_plot代码,在aes()里添加group = Name,让图层包含分面变量:
rpe_plot <- rpe %>% ggplot(aes(Date, RPE, group = Name)) + geom_col() + labs(title = "RPE for the Week", x = "", y = "") + facet_wrap(~Name, scales = "free")
如果需要视觉区分,也可以用fill = Name并隐藏重复图例:
rpe_plot <- rpe %>% ggplot(aes(Date, RPE, fill = Name)) + geom_col() + labs(title = "RPE for the Week", x = "", y = "") + facet_wrap(~Name, scales = "free") + guides(fill = "none") # 移除图例,避免重复展示Name信息
方法2:确保数据对象正确加载到RMarkdown环境
- 修正R脚本开头的数据赋值(你提供的代码中缺失了
rpe <-):
rpe <- structure(list(Date = structure(c(19368, 19368, 19368, 19368, 19368, 19368, 19368, 19368, 19369, 19369, 19369, 19369, 19369, 19369, 19369, 19366, 19366, 19366, 19366, 19366, 19366, 19366, 19366), class = "Date"), Name = c("Player 1", "Player 2", "Player 3", "Player 5", "Player 7", "Player 10", "Player 11", "Player 12", "Player 11", "Player 7", "Player 10", "Player 3", "Player 2", "Player 1", "Player 12", "Player 10", "Player 12", "Player 3", "Player 5", "Player 7", "Player 2", "Player 1", "Player 11"), RPE = c(6, 5, 6, 5, 5, 4, 5, 6, 4, 6, 6, 7, 6, 7, 5, 5, 5, 4, 4, 5, 5, 6, 4), Legginess = c(7, 6, 6, 6, 4, 5, 8, 5, 8, 5, 5, 7, 6, 6, 5, 4, 4, 4, 4, 3, 2, 5, 4), Breathlessness = c(5, 5, 5, 4, 5, 3, 6, 6, 3, 4, 6, 3, 6, 5, 4, 5, 6, 5, 4, 4, 6, 6, 6)), row.names = c(NA, -23L), class = c("tbl_df", "tbl", "data.frame"))
- 在RMarkdown中source脚本时,指定加载到全局环境:
source(here("RPE_Dashboard/RPE_Script.R"), local = knitr::knit_global())
方法3:临时验证绘图逻辑
如果以上方法仍有问题,可先将脚本中的绘图代码直接复制到RMarkdown代码块中运行,排除source带来的环境问题,确认逻辑无误后再拆分回脚本。
内容的提问来源于stack exchange,提问作者Josh
相关产品推荐
相关产品推荐

