首页 > 解决方案 > 动画点直方图,通过观察构建观察(在 R 中使用 gganimate)

问题描述

我想从正态分布中采样点,然后使用gganimate包一个一个地构建一个点图,直到最后一帧显示完整的点图。

适用于约 5,000 - 20,000 点的较大数据集的解决方案至关重要。

这是我到目前为止的代码:

library(gganimate)
library(tidyverse)

# Generate 100 normal data points, along an index for each sample 
samples <- rnorm(100)
index <- seq(1:length(samples))

# Put data into a data frame
df <- tibble(value=samples, index=index)

df 看起来像这样:

> head(df)
# A tibble: 6 x 2
    value index
    <dbl> <int>
1  0.0818     1
2 -0.311      2
3 -0.966      3
4 -0.615      4
5  0.388      5
6 -1.66       6

静态图显示正确的点图:

# Create static version
plot <- ggplot(data=df, mapping=aes(x=value))+
          geom_dotplot()

但是,该gganimate版本没有(见下文)。它只将点放在 x 轴上,不堆叠它们。

plot+
  transition_reveal(along=index)

静态图

在此处输入图像描述

与此类似的东西是理想的:信用:https ://gist.github.com/thomasp85/88d6e7883883315314f341d2207122a1 在此处输入图像描述

标签: rggplot2data-visualizationgganimate

解决方案


另一种选择是用另一个几何图形绘制点。您将需要首先对您的数据进行一些计数(和分箱),但它不需要使您的数据更长。

例如,您可以使用geom_point,但挑战将是让您的点的尺寸正确,因此它们接触/不接触。这取决于设备/文件大小。

但你也可以只ggforce::geom_ellipse用来画你的点:)

geom_point(设备尺寸的反复试验)

library(tidyverse)
library(gganimate)

set.seed(42)
samples <- rnorm(100)
index <- seq(1:length(samples))
df <- tibble(value = samples, index = index)

bin_width <- 0.25

count_data <- # some minor data transformation
  df %>%
  mutate(x = plyr::round_any(value, bin_width)) %>%
  group_by(x) %>%
  mutate(y = seq_along(x))

plot <-
  ggplot(count_data, aes(group = index, x, y)) + # group by index is important
  geom_point(size = 5)

p_anim <- 
  plot +
  transition_reveal(index)

animate(p_anim, width = 550, height = 230, res = 96)

geom_ellipse(完全控制点大小)

library(ggforce)
plot2 <- 
  ggplot(count_data) +
  geom_ellipse(aes(group = index, x0 = x, y0 = y, a = bin_width/2, b = 0.5, angle = 0), fill = 'black') +
  coord_equal(bin_width) # to make the dots look nice and round

p_anim2 <- 
  plot2 +
  transition_reveal(index) 

animate(p_anim2) 

在您提供给 thomas 的惊人示例的链接中更新,您可以看到他使用了类似的方法 - 他使用 geom_circle 而不是 geom_ellipse,我之所以选择它是因为可以更好地控制垂直和水平半径。

要获得“下降水滴”效果,您将需要transition_states较长的持续时间和每秒许多帧。

p_anim2 <- 
  plot2 +
  transition_states(states = index, transition_length = 100, state_length = 1) +
  shadow_mark() +
  enter_fly(y_loc = 12) 

animate(p_anim2, fps = 40, duration = 20) 

reprex 包(v0.3.0)于 2020-04-29 创建

一些灵感来自:ggplot dotplot:geom_dotplot 的正确用途是什么?


推荐阅读