gpt4 book ai didi

r - 如何在 gganimate 包 (R) 中使用多列作为动画的框架?

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

我正在尝试使用 R 的 gganimate 包来创建一堆直方图的动画,其中动画的每一帧都显示图像的直方图。我有大约 400 张图片,所以大约有 400 列。我的数据如下所示:

| bins.left | bins.right | hist1 | hist 2 | ... | hist n |

如您所见,我需要在每一帧中将每一列视为直方图的 Y 值。换句话说,我的动画应该遍历列。

但是我在互联网上研究过的所有例子,似乎都只考虑一列作为框架的标识符。例如在 this example :

mapping <- aes(x = gdpPercap, y = lifeExp, 
size = pop, color = continent,
frame = year)
p <- ggplot(gapminder, mapping = mapping) +
geom_point() +
scale_x_log10()

属性“Year”被视为迭代器。该数据如下所示:

  country continent  year lifeExp      pop gdpPercap
<fctr> <fctr> <int> <dbl> <int> <dbl>
1 Afghanistan Asia 1952 28.801 8425333 779.4453
2 Afghanistan Asia 1957 30.332 9240934 820.8530
3 Afghanistan Asia 1962 31.997 10267083 853.1007
4 Afghanistan Asia 1967 34.020 11537966 836.1971
5 Afghanistan Asia 1972 36.088 13079460 739.9811
6 Afghanistan Asia 1977 38.438 14880372 786.1134

我不想修改我的数据以适应这种模式的原因是,如果我将所有直方图都放在一列中,我的数据框将非常长(长度 = ~ 16000 * 400)并且很难处理。此外,以如此困惑的方式保存我的数据并不直观。我相信我的问题一定有一个简单的解决方案。非常感谢任何建议。

最佳答案

正如@Marius 所说,如果您的数据是长格式的,您就可以完成这项工作。下面我创建一些假数据,然后制作动画图。

library(tidyverse)
theme_set(theme_classic())
library(gganimate)

这是包含 10 列值的假数据,我们希望将其转换为直方图。

set.seed(2)
dat = replicate(10, runif(100)) %>% as.data.frame

数据是宽格式的,所以首先我们用gather函数把它转换成长格式:

d = dat %>% gather(key, value)

在新的长格式中,key 列告诉我们数据最初来自哪个直方图列。我们将使用它作为我们的 frame 并运行 geom_histogram:

p = ggplot(d, aes(value, frame=key)) +
geom_histogram()

gganimate(p)

你可以看到这不是我们想要的。 ggplot 实际上从所有数据生成了一个直方图,动画只是连续向我们展示了每个堆栈中来自 key 的每个值的部分。

enter image description here

我们需要一种方法让 ggplot 创建单独的直方图并为它们制作动画。我们可以通过预先合并数据并使用 geom_rect 创建直方图条来做到这一点:

d = dat %>% gather(key, value) %>% 
mutate(bins = cut(value, breaks=seq(0,1,0.1),
labels=seq(0,0.9,0.1) + 0.05, include.lowest=TRUE),
bins = as.numeric(as.character(bins))) %>%
group_by(key, bins) %>%
tally

p = ggplot(d, aes(xmin=bins - 0.048, xmax=bins + 0.048, ymin=0, ymax=n, frame=key)) +
geom_rect() +
scale_y_continuous(limits=c(0, max(d$n)))

gganimate(p)

enter image description here

针对您的评论,我认为您不能将 gganimate 用于宽格式数据。 gganimate 需要单个 frame 列,这需要长格式的数据。但是,gganimateanimation 包的包装器,您可以使用 for 循环和 saveGIF 函数直接创建动画 GIF 文件:

library(animation)

saveGIF({
for (i in names(dat)) {
p = ggplot(dat, aes_string(i)) +
geom_histogram(breaks=seq(0,1,0.1))
print(p)
}
}, movie.name="test.gif")

enter image description here

关于r - 如何在 gganimate 包 (R) 中使用多列作为动画的框架?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49247591/

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