1

我希望生成一个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)

有什么建议么?

4

1 回答 1

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)

在此处输入图像描述

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

为了快速做到这一点,我取最后一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)

在此处输入图像描述

于 2018-10-18T19:03:49.927 回答