gpt4 book ai didi

r - 使用 gganimate 构建堆叠直方图

转载 作者:行者123 更新时间:2023-12-04 16:34:27 25 4
gpt4 key购买 nike

我正在尝试显示随着时间的推移构建的直方图。它将从 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

最佳答案

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

关于r - 使用 gganimate 构建堆叠直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55861236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com