使用gganimate绘制收敛图时遇invalid times参数错误的解决方法
解决gganimate绘制收敛图时的
invalid 'times' argument错误 错误提示
Error in rep(seq_len(nrow(polygon)), splits + 1) :
invalid 'times' argument
问题原因
你的代码中,部分facet对应的数据集只有1个数据点(比如facet=1时仅包含1行数据),而geom_line()需要至少2个点才能生成折线。gganimate在处理这种无法生成有效折线的图层时,触发了内部参数错误。
解决方案
将geom_line()替换为geom_path(),并配合geom_point()兼容单数据点的情况。修改后的绘图代码如下:
anim <- df_facet %>% ggplot(aes(x = i, y = cum_mean))+ geom_path() + # 替代geom_line,自动适配单数据点场景 geom_point(size = 2) + # 显示单个数据点,提升可视化效果 ggplot2::ylim(c(0,1)) + ggplot2::xlim(c(0,n)) + gganimate::transition_states(facet)
额外优化(可选)
可以简化数据构造代码,避免手动逐个head()再bind_rows(),用tidyr更高效生成数据集:
library(tidyr) df_facet <- df_unif %>% mutate(facet = map(i, ~seq_len(.x))) %>% unnest(facet) %>% group_by(facet) %>% slice(seq_len(facet)) %>% ungroup()
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

