3

我开始学习如何使用这个gridSVG包来创建动画 SVG 图。作为测试,我想为一组点设置动画,从开始位置移动到结束位置。该示例大致基于包的第一个小插图中的示例。

首先,一些数据:

n_points <- 20
start <- data.frame(
  x = runif(n_points),
  y = runif(n_points)
)
end <- data.frame(
    x = runif(n_points),
    y = runif(n_points)
)

基本思想似乎是“绘制一个新页面,添加第一帧的内容,制作动画,然后保存到 SVG”。我的第一次尝试将所有点都画在同一个地方。我不确定如何判断grid.animate每个点都需要单独移动。

grid.newpage()
with(start, 
  grid.points(x, y, default.units = "npc", name = "points")
)
grid.animate(
  "points", 
  x = c(start$x, end$x),
  y = c(start$y, end$y)
)
gridToSVG("point_test1.svg")

我可以通过在自己的 grob 中绘制每个点来解决这个问题,使用lapply. 这行得通,但感觉很笨拙——应该有一种矢量化的方式来做这件事。

grid.newpage()
lapply(seq_len(n_points), function(i)
{
  gname = paste("points", i, sep = ".")
  with(start, 
    grid.points(x[i], y[i], default.units = "npc", name = gname)
  )
  grid.animate(
    gname, 
    x = c(start$x[i], end$x[i]),
    y = c(start$y[i], end$y[i])
  )
})
gridToSVG("point_test2.svg")

我也尝试过使用animUnit,但我不知道如何指定id参数。

grid.newpage()
with(start, 
  grid.points(x, y, default.units = "npc", name = "points")
)
x_points <- animUnit(
  unit(c(start$x, end$x), "npc"),
  timeid = rep(1:2, each = n_points),
  id = rep(1:2, n_points)
)        
y_points <- animUnit(
  unit(c(start$y, end$y), "npc"),
  timeid = rep(1:2, each = n_points),
  id = rep(1:2, n_points)
)        
grid.animate(  #throws an error: Expecting only one value per time point
  "points", 
  x = x_points,
  y = y_points
)
gridToSVG("point_test3.svg")

我可以在单个 grob 中为多个点设置动画,或者在没有循环的情况下为点设置动画吗?

4

1 回答 1

3

这对我有用animUnit

grid.newpage()
with(start, 
  grid.points(x, y, default.units = "npc", name = "points")
)
x_points <- animUnit(
  unit(c(start$x, end$x), "npc"),
  #timeid = rep(1:2, each = n_points),
  id = rep(1:20, 2)
)        
y_points <- animUnit(
  unit(c(start$y, end$y), "npc"),
  #timeid = rep(1:2, each = n_points),
  id = rep(1:20, 2)
)        
grid.animate(  #throws an error: Expecting only one value per time point
  "points", 
  x = x_points,
  y = y_points
)

您为两点指定 id,而不是二十点。我对小插图的解读是,要使用每个 grob 的单个 x 值对多个 grobs 进行动画处理,您只需要指定 id。

于 2011-12-21T17:33:01.163 回答