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

使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:05:30