【问题标题】:How can I animate a scatterplot using the animation package for R?如何使用 R 的动画包为散点图设置动画?
【发布时间】:2017-01-01 08:50:56
【问题描述】:

到目前为止,我所做的只是创建一个包含 30 个相同帧的 gif,最后一帧具有黄土曲线。

但是,我想要一个单独绘制每个点的动画(即,第 1 帧打印第一个观察结果,第 2 帧打印第一个和第二个观察结果,等等)。此外,在动画快结束时(一旦绘制了所有点和黄土),我希望添加将点连接到黄土曲线的线段。

我基本上想从 ISLR 为 this plot 制作动画。

代码

```{r, echo=FALSE, message=FALSE, results='hide'}
library(animation)

income <- read.csv("Datasets/Income1.csv")

x <- income$Education
y <- income$Income

loess.model <- (loess.smooth(x,y))

saveGIF({
  for(i in 1:30)
    plot(y~x)
  lines(loess.model)
}, interval = 0.15, movie.name = "f.gif", dir(path = "animations"))
```

【问题讨论】:

  • 您是否收到错误消息?
  • 仅当我包含分段线(segments(x,fitted(loess.model),x,y))。删除该位,代码应该运行。
  • 刚刚删除了分段线,现在应该可以正常运行了。

标签: r animation


【解决方案1】:

这是一种方法:

library(animation)

x <- cars$speed
y <- cars$dist

l <- loess(y~x)
y_ <- predict(l, newdata = x)

ylim <- range(y)
xlim <- range(x)
p <- function(x,y, ...) 
  plot(x, y, ylim=ylim, xlim=xlim, xlab="x", ylab="y", ...)
times <- c(1, rep(0.1, length(x)), 1, 5) # frame 1 for 1 sec, 2-51 à 0.1 sec, ...

saveGIF({
  p(x,y) # frame 1
  for(i in seq_along(x)) p(x[1:i], y[1:i]) # frames 2-51
  p(x,y);lines(x, y_) # frame 52
  p(x,y);lines(x, y_);segments(x, y_, x, y, col = "red") # frame 53
}, interval = times)

【讨论】:

  • 谢谢,太好了!
猜你喜欢
  • 2018-07-07
  • 2016-06-01
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
  • 1970-01-01
  • 2021-07-04
  • 2019-12-28
相关资源
最近更新 更多