我正试着用Gganimate制作R中的一个三元情节的动画,我面对着一堵墙.

library(tidyverse)
library(gganimate)
library(ggtern)
#> Registered S3 methods overwritten by 'ggtern':
#>   method           from   
#>   grid.draw.ggplot ggplot2
#>   plot.ggplot      ggplot2
#>   print.ggplot     ggplot2
#> --
#> Remember to cite, run citation(package = 'ggtern') for further info.
#> --
#> 
#> Attaching package: 'ggtern'
#> The following objects are masked from 'package:ggplot2':
#> 
#>     aes, annotate, ggplot, ggplot_build, ggplot_gtable, ggplotGrob,
#>     ggsave, layer_data, theme_bw, theme_classic, theme_dark,
#>     theme_gray, theme_light, theme_linedraw, theme_minimal, theme_void

data=tibble(x=runif(200),  y = runif(200),  z = runif(200), time=rep(seq(1:10),20))

ggtern(data, aes(x,y,z)) +
  geom_point() +
  theme_rgbw() +
  stat_density_tern(geom = 'polygon',
                    aes(fill  = ..level..,
                        alpha = ..level..), bdl=0.001) +
    scale_fill_gradient(low = "blue",high = "red")  +
  guides(color = "none", fill = "none", alpha = "none") 
#> Warning: Removed 1 rows containing non-finite values (StatDensityTern).

创建于2022-11-04年第reprex v2.0.2

这是我的代码中失败的部分.我想让这些点在每个时间点上移动.

ggtern(data, aes(x,y,z)) +
  geom_point() +
  theme_rgbw() +
  stat_density_tern(geom = 'polygon',
                    aes(fill  = ..level..,
                        alpha = ..level..), bdl=0.001) +
    scale_fill_gradient(low = "blue",high = "red")  +
  guides(color = "none", fill = "none", alpha = "none") +
transition_states(transition_length = 1, time)

推荐答案

使用gganimate时出现了一个问题(参见this个未回答的堆栈溢出问题).

当然,仍然可以用老式的方法创建ggPlot动画:编写一组PNG文件,然后使用magick将它们缝合到一个PNG文件中:

library(tidyverse)
library(gganimate)
library(ggtern)
library(magick)

data = tibble(x=runif(400),  y = runif(400),  
            z = runif(400), time = rep(seq(1:20), 20))


for(i in 1:20) {
  p <- ggtern(data[data$time == i, ], aes(x, y, z)) +
    geom_point() +
    theme_rgbw() +
    stat_density_tern(geom = 'polygon',
                      aes(fill = ..level.., alpha = ..level..), bdl = 0.001) +
    scale_fill_gradient(low = "blue",high = "red")  +
    guides(color = "none", fill = "none", alpha = "none") 
  
  ggsave(paste0('ggtern', i, '.png'), p)
}

list.files(pattern = 'ggtern\\d+\\.png', full.names = TRUE) %>% 
  image_read() %>% 
  image_join() %>% 
  image_animate(fps=4) %>% 
  image_write("ggtern.gif") 

现在我们有了以下文件:

ggtern.gif

enter image description here

R相关问答推荐

使用gggrassure减少地块之间的空间

如何动态更新selectizeInput?

如何根据嵌套元素的名称高效而优雅地确定它属于哪个列表?

如果可能,将数字列转换为整数,否则保留为数字

在rpart. plot或fancyRpartPlot中使用带有下标的希腊字母作为标签?

提取一个列表中单个列的重复观察结果R

如何在R中描绘#符号?

如何通过判断数据框的一列来压缩另一列?

Geom_arcbar()中出错:找不到函数";geom_arcbar";

远离理论值的伽马密度曲线下面积的近似

在具有多个响应变量的比例堆叠条形图上方添加总计

如何构建一个for循环来循环处理动物ID?

使用geom_sf跨越日期线时的闭合边界

如何从嵌套数据中自动创建命名对象?在R中

R-找出存在其他变量的各种大小的所有组合

将数据从一列转换为按组累计计数的单个虚拟变量

具有自定义仓位限制和计数的GGPLATE直方图

如何计算多个变量的百分比与总和的百分比?

R+MICESS:我想编写一个函数,用于在补偿后从MICES MIDS对象中提取信息

检测R中不符合对数函数的离群点