【问题标题】:Building a stacked histogram with gganimate使用 gganimate 构建堆叠直方图
【发布时间】:2019-04-26 14:44:58
【问题描述】:

我正在尝试显示随着时间的推移构建的直方图。它会从 1952 年的数据开始,然后每年更新直方图,并不断增长。

路径似乎是 gganimate,我想使用 transition_reveal 随着时间的推移慢慢揭示更多数据。这似乎不起作用。

假设我从这个开始:

library(gapminder)
library(tidyverse)
library(gganimate)

ggplot(gapminder, 
       aes(lifeExp, fill = fct_rev(factor(year)), group = fct_rev(factor(year)))) +
  geom_histogram(position = "stack", bins = 20) +
  transition_reveal(year)  

严重失败。

我可以和transition_layer 拼凑一些东西,就像这样:

ggplot(gapminder, aes(lifeExp, fill = fct_rev(factor(year)))) +
  geom_histogram(position = "stack", bins = 20, 
                 data = filter(gapminder, year<= 1952)) +
  geom_histogram(position = "stack", bins = 20, 
                 data = filter(gapminder, year<= 1957)) +
  geom_histogram(position = "stack", bins = 20, 
                 data = filter(gapminder, year<= 1962)) +
  geom_histogram(position = "stack", bins = 20, 
                 data = filter(gapminder, year<= 1967)) +
  geom_histogram(position = "stack", bins = 20, 
                 data = filter(gapminder, year<= 1972)) +
  geom_histogram(position = "stack", bins = 20, 
                 data = filter(gapminder, year<= 1977)) +
  transition_layers()  

它产生了预期的结果,但很笨重。有没有更便携的方式?

这是我正在寻找的 gif 图像:

【问题讨论】:

    标签: r ggplot2 gganimate


    【解决方案1】:

    我无法使用 geom_histogram 来计算它,但我可以通过从 geom_rect 制作堆叠直方图来计算。

    bin_yrs = 2
    a <- gapminder %>%
      count(year, life_bin = floor(lifeExp / bin_yrs) * bin_yrs) %>%
      complete(year, life_bin, fill = list(n = 0)) %>%
      arrange(year, life_bin) %>%
      group_by(life_bin) %>%
      mutate(dummy = lag(cumsum(n), default = 0)) %>%
      ungroup() %>%
    
      ggplot(aes(xmin = life_bin, 
                 xmax = life_bin + bin_yrs,
                 ymin = dummy, 
                 ymax = dummy + n,
                 fill = as.factor(year))) +
      geom_rect() +
      transition_manual(year) +
      shadow_trail()
    animate(a, nframes = 12, fps = 4, width = 600, height = 300)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-12
      • 2015-11-28
      • 2016-12-19
      • 2012-06-04
      • 2021-11-24
      • 1970-01-01
      • 2022-01-16
      相关资源
      最近更新 更多