我试图显示随时间变化的直方图。可以从1952年的数据开始,然后每年更新直方图,然后不断增长。
这条路似乎很费力,我认为使用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文件:
答案 0 :(得分:3)
我无法使用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)