【问题标题】:How can I make an animation in R showing a histogram with different bin sizes?如何在 R 中制作显示具有不同 bin 大小的直方图的动画?
【发布时间】:2020-04-18 18:08:32
【问题描述】:

我想使用gganimate(),但找不到可行的解决方案。

我最终成功地创建了一些东西 - 使用 animation 包。我能够创建 GIF 和视频输出 - 但都没有我希望的那么流畅或那么好。

输出非常不稳定——如果我想使用基本的“hist”函数显示 20 个不同的中断,动画只会显示其中的一半左右。您可以看到 GIF 遍历所有 # 个 bin,但图不会针对每一步更新。

这是我的代码的GIF output

library('ggplot2')
library('animation')

psd_1 <- data.frame(rnorm(5000, 100, 15))

colnames(psd_1)[1] <- "passengers"

ani.options(interval=.25, nmax=20)

a = saveGIF(
  {
    for (i in c(1:20)) {
      hist(psd_1$passengers, breaks=i, main=paste("Histogram with ",i, " bins"),
           xlab="Total Passengers")
    }
  }
  , movie.name="wodies.gif")

【问题讨论】:

  • 请注意,将break= 设置为单个数值并不能保证中断的数量(“该数字只是一个建议”)。检查?hist 帮助页面。如果您需要正好有那么多垃圾箱,则需要明确设置休息时间。如需更多帮助,您应该提供reproducible example
  • 包名是animation,不是animate
  • 另外,把ani.options(interval = 0.25, nmax = 50)放在saveGIF之外,这个只设置一次。
  • 你想要的输出是什么?
  • @RuiBarradas - 我更新了问题中的文本以引用正确的包,并更改了我的代码以将 ani.options 移到 saveGIF 之外

标签: r histogram bin gganimate


【解决方案1】:

正如我在 cmets 中提到的,如果您将单个数字传递给 breaks=,它并不能保证中断的数量,这只是一个建议。如果你想设置一个准确的数字,你需要传入一个中断向量。你可以这样做

a = saveGIF(
  {
    for (i in c(1:20)) {
      hist(psd_1$passengers, 
           breaks=seq(min(psd_1$passengers), max(psd_1$passengers), length.out=i), 
           main=paste("Histogram with ",i, " bins"), 
           xlab = "Total Passengers")  }
  }
  , movie.name = "wodies.gif")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    相关资源
    最近更新 更多