首页 > 解决方案 > Can I add a gif on top of another gif in R?

问题描述

I've got two gifs that I've generated with ggplot and gganimmate. One is a world map and the other is a normal bar graph. I'm trying to show the bar graph in a viewport inside of the world map and have them be animated at the same rate. Since they're both created using the same dataset, I thought I could use gganimate to animate them at the same time.

I'm looking to make something like this:

在此处输入图像描述

The bar graph uses transition_reveal() and the map uses transition_manual() so I can't animate them together.

Is there a simpler way to animate two plots at the same time? Or can I somehow get both to use the same transition_*() function?

Code used for map:

plot_anim = ggplot(data = dat) +
  geom_sf(aes(geometry = geometry,
              fill = Deaths),
          alpha = 0.3) +
  geom_point(aes(x = X, y = Y,
                 size = ifelse(Confirmed==0, NA, Confirmed)),
             shape = 21,
             colour = "turquoise",
             alpha = 0.5,
             fill = "turquoise") +
  transition_manual(Date)

animate(p, renderer = gifski_renderer(loop = T))

Code used for bar graph:

plot_anim2 = ggplot(data = totals) +
  geom_bar(aes(x = Date, y = Number,
               fill = Type),
           stat = "identity",
           position = "stack") +
  transition_time(Date) +
  shadow_mark(past = T)  

animate(plot_anim2, renderer = gifski_renderer(loop = TRUE))

Edit:

Some data:

> head(dat)
        Date             Country Confirmed Recovered Deaths      pop cases_per_mil          X         Y
1 2020-01-22         Afghanistan         0         0      0 29117000             0  66.004734  33.83523
2 2020-01-22             Albania         0         0      0  3195000             0  20.049834  41.14245
3 2020-01-22             Algeria         0         0      0 35423000             0   2.617323  28.15894
4 2020-01-22             Andorra         0         0      0    84082             0   1.560544  42.54229
5 2020-01-22              Angola         0         0      0 18993000             0  17.537368 -12.29336
6 2020-01-22 Antigua and Barbuda         0         0      0    89000             0 -61.794693  17.27750
                        geometry
1 MULTIPOLYGON (((74.89131 37...
2 MULTIPOLYGON (((20.06396 42...
3 MULTIPOLYGON (((8.576563 36...
4 MULTIPOLYGON (((1.706055 42...
5 MULTIPOLYGON (((14.19082 -5...
6 MULTIPOLYGON (((-61.71606 1...
> head(totals)
# A tibble: 6 x 3
  Date       Type      Number
  <date>     <chr>      <int>
1 2020-01-22 Confirmed    555
2 2020-01-23 Confirmed    654
3 2020-01-24 Confirmed    941
4 2020-01-25 Confirmed   1434
5 2020-01-26 Confirmed   2118
6 2020-01-27 Confirmed   2927

标签: rggplot2spatialgganimate

解决方案


实现此目的的一种方法是将您的 gif 文件保存到 www 文件夹,并在空白的 Shiny 应用程序中使用 absolutePanel 显示它们。您可以让条形图褪色,而另一个不褪色。下面是一个静态世界地图,其中两个图像显示在绝对面板中。当它们浮动时,您可以将它们拖放到您想要的位置。

输出


推荐阅读