使用gganimate生成堆叠直方图

5

我试图展示一个随着时间累积的柱状图。它会从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演示: Growing stacked histogram
1个回答

5

我无法使用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)

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接