是否有可能生成随机数字的gganimate图?

Ber*_*rdo 1 pi r ggplot2 gganimate

我希望生成一个gganimate对象,显示特定范围内的n个随机点.另一个限制是它应该绘制2^n点,意味着2, 4, 8, 16, 32, 64...点.我这样做是为了计算小数,pi但我想绘制这个动画,这样我就可以展示它如何以更好的方式给出更多的随机数来改善结果.

这是我到目前为止:

results <- c()
for(i in c(1:20)) {
  r <- 1
  limit <- 2^i
  points <- data.frame(
    x = runif(limit, -r, r), 
    y = runif(limit, -r, r))
  points$d <- sqrt(points$x^2 + points$y^2)
  points$type <- ifelse(points$d < r, "c", "s")
  picalc <- 4 * length(points$type[points$type=="c"]) / limit
  error <- pi - picalc
  label <- paste0('Pi calc : ', round(picalc, 6), '\nError : ', round(error, 6))
  iter <- data.frame(n = limit, picalc = picalc, error = error, label = label)
  results <- rbind(results, iter)
}

# GGANIMATE
library(ggplot2)
library(gganimate)
p <- ggplot(results, aes(x = runif(n, -1, 1), y = runif(n, -1, 1))) +
  geom_point(lwd = 2, alpha = 0.3) + 
  theme_minimal() +
  geom_text(aes(x = 0, y = 0, label = label), size = 5) + 
  labs(caption = 'Number of random points : {frame_time}') + 
  transition_time(n)
animate(p, nframes =  nrow(results), fps = 5)
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Jon*_*ing 7

这就是我如何"以更好的方式给出更多随机数字来显示它如何改善结果."

library(ggplot2)
library(gganimate)
p <- ggplot(results, aes(x = n, y = error)) +
  geom_point(lwd = 2, alpha = 0.3) + 
  theme_minimal() +
  geom_text(aes(x = 0, y = 0, label = label), size = 5, hjust = 0) + 
  scale_x_log10(breaks = c(2^(1:4), 4^(2:10)), minor_breaks = NULL) +
  labs(caption = 'Number of random points : {2^frame}') + 
  transition_manual(n) +
  shadow_trail(exclude_layer = 2)
animate(p, nframes =  nrow(results), fps = 5)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

要显示问题中描述的图片类型,您需要使用他们所属的框架标记点.(另外,正如目前所写的那样,每次迭代都会重新随机分配点.最好先设置所有点,然后在增加窗口大小时坚持使用这些点来计算结果.)

为了快速完成这个,我将采用最后一points帧(因为它i在循环结束时存在),并为它应该属于的帧添加一个数字.然后我可以使用绘制每个帧的点transition_manual,并使用保留过去的帧shadow_trail.

注意,如果用1M点运行它,ggplot将比我关心的慢,所以我做了一个删节版本,最多2 ^ 15 = 32k.

# Note, I only ran the orig loop for 2^(1:15), lest it get too slow
points2 <- points %>%
  mutate(row = row_number(),
         count = 2^ceiling(log2(row)))

point_plot <- ggplot(points2, 
                     aes(x = x, y = y, color = type, group = count)) +
  geom_point(alpha = 0.6, size = 0.1) + 
  theme_minimal() +
  labs(caption = 'Number of random points : {2^(frame-1)}') +
  transition_manual(count) +
  shadow_trail()
animate(point_plot, nframes = 15, fps = 2)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述