R 中的动画直方图

Animate Histograms in R

我正在尝试在 R 中制作直方图动画。我创建了以下数据集:

   library(ggplot2)
library(gganimate)

a = abs(rnorm(100,10,10))
b = abs(rnorm(100,10,10))
i = 1
c = data.frame(a,b,i)

a = abs(rnorm(100,10,10))
b = abs(rnorm(100,10,10))
i = 2
d = data.frame(a,b,i)

a = abs(rnorm(100,10,10))
b = abs(rnorm(100,10,10))
i = 3
e = data.frame(a,b,i)

#data
g = rbind(c,d,e)

我能够在 base R 和 ggplot 中制作静态直方图:

myplot1 = plot(g$a, type = "h")


myplot2 = ggplot(g, aes(x=a)) + 
  geom_histogram(binwidth=1)

问题是当我尝试为这些图表设置动画时(这是 3 个图表:i = 1,2,3):

#first attempt
animateplot <- myplot1 + transition_time(i)

animateplot

NULL

#second attempt

anim <- myplot2 + transition_manual(g$i) +
  ease_aes("linear") +
  enter_fade() +
  exit_fade()

anim

NULL

有人可以告诉我如何制作这些图表的动画并将动画保存为 gif 或 html 文件吗?

谢谢!

ggplot(g, aes(x=a)) + 
  geom_histogram(binwidth=1) +
  transition_states(i)

或使用更多选项的变体:

# alternative fake data
g <- data.frame(a = c(rnorm(500,10,5), rnorm(2000, 20, 30), rnorm(180, 50, 2)),
                i = c(rep(1, 500), rep(2, 2000), rep(3, 180)))

animate(
  ggplot(g, aes(x=a)) + 
  geom_histogram(binwidth=1) +
  transition_states(i, state_length = 0.2) +
  labs(title = "Group: {closest_state}"),
  fps = 25)