用 plotly 动画直方图

Posted

技术标签:

【中文标题】用 plotly 动画直方图【英文标题】:Animating Histograms with plotly 【发布时间】:2021-11-27 00:39:47 【问题描述】:

我正在尝试创建大数定律的动画演示,我想在其中显示随着样本量增加而收敛到密度的直方图。

我可以使用 R shiny 来做到这一点,在样本大小上放置一个滑块,但是当我尝试使用样本大小作为框架来设置情节动画时,我在 ggploty 的内部深处遇到了一个错误。下面是示例代码:

library(tidyverse)
library(plotly)
XXX <- rnorm(200)
plotdat <- bind_rows(lapply(25:200, function(i)   data.frame(x=XXX[1:i],f=i)))
hplot <- ggplot(plotdat,aes(x,frame=f)) + geom_histogram(binwidth=.25)
ggplotly(hplot)

最后一行返回错误。 Error in -data$group : invalid argument to unary operator.

我不确定应该从哪里获取 data$group(这个值已经在 ggplotly 的其他调用中为我神奇地设置了)。

【问题讨论】:

【参考方案1】:

跳过最初的 ggplot 直接进入 plotly,这对你有用吗?

plotdat %>%
  plot_ly(x=~x,
          type = 'histogram',
          frame = ~f) %>%
  layout(yaxis = list(range = c(0,50)))

或者,使用您的原始语法,我们可以添加一个似乎可以防止错误的位置规范。这个版本看起来更好,具有标准的 ggplot 格式和补间动画。

hplot <- ggplot(plotdat, aes(x, frame = f)) + 
  geom_histogram(binwidth=.25, position = "identity")
ggplotly(hplot) %>%
  animation_opts(frame = 100) # minimum ms per frame to control speed

(我不知道为什么会这样修复它,但是当我用谷歌搜索你的错误时,我在 github 上看到了一个通过指定位置解决的情节问题,它似乎也修复了这里的错误。https://github.com/plotly/plotly.R/issues/1544)

【讨论】:

以上是关于用 plotly 动画直方图的主要内容,如果未能解决你的问题,请参考以下文章