如何在Shiny中创建和显示动态GIF?

8

我可以将保存的文件加载为图像,但无法直接使用gganimate。了解其他呈现GIF的方法也很好,但特别是知道如何呈现gganimate将真正解决我的问题。

library(gapminder)
library(ggplot2)
library(shiny)
library(gganimate)
theme_set(theme_bw())

ui <- basicPage(
    plotOutput("plot1")
)

server <- function(input, output) {
    output$plot1 <- renderPlot({
        p = ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent, frame = year)) +
  geom_point() +
  scale_x_log10()

       gg_animate(p)

    })

}

shinyApp(ui, server)
2个回答

11

现在有一个更新的 gganimate 版本,@kt.leap的答案已经过时了。这是对于新版本的 gganimate 我所使用的方法:


现在有一个更新的 `gganimate` 版本,@kt.leap 的回答已经过时了。这是对于新版本的 `gganimate` 我所使用的方法:
library(gapminder)
library(ggplot2)
library(shiny)
library(gganimate)
theme_set(theme_bw())

ui <- basicPage(
    imageOutput("plot1"))

server <- function(input, output) {
    output$plot1 <- renderImage({
    # A temp file to save the output.
    # This file will be removed later by renderImage
    outfile <- tempfile(fileext='.gif')

    # now make the animation
    p = ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, 
      color = continent)) + geom_point() + scale_x_log10() +
      transition_time(year) # New

    anim_save("outfile.gif", animate(p)) # New

    # Return a list containing the filename
     list(src = "outfile.gif",
         contentType = 'image/gif'
         # width = 400,
         # height = 300,
         # alt = "This is alternate text"
         )}, deleteFile = TRUE)}

shinyApp(ui, server)

我收到一个错误信息:“不支持gg对象的动画”。 - jlp
@jlp 这段代码对我仍然有效。请检查您是否已更新所有内容,包括 gifski 包。https://stackoverflow.com/questions/58336048/error-in-animate-default-animation-of-gg-objects-not-supported - Phil

5
我遇到了同样的问题,只找到了你的问题,但是你的措辞提醒我renderPlot很挑剔:它不会将任何图像文件发送到浏览器——图像必须由使用R的图形输出设备系统的代码生成。其他创建图像的方法无法通过renderPlot()发送...在这种情况下的解决方案是renderImage()函数。来源 从该文章修改代码,您将得到以下结果:
library(gapminder)
library(ggplot2)
library(shiny)
library(gganimate)
theme_set(theme_bw())

ui <- basicPage(
    imageOutput("plot1"))

server <- function(input, output) {
    output$plot1 <- renderImage({
    # A temp file to save the output.
    # This file will be removed later by renderImage
    outfile <- tempfile(fileext='.gif')

    # now make the animation
    p = ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, 
      color = continent, frame = year)) + geom_point() + scale_x_log10()

    gg_animate(p,"outfile.gif")

    # Return a list containing the filename
     list(src = "outfile.gif",
         contentType = 'image/gif'
         # width = 400,
         # height = 300,
         # alt = "This is alternate text"
         )}, deleteFile = TRUE)}

shinyApp(ui, server)

抱歉回复晚了,生活有些忙碌。您的解决方案需要将文件保存到磁盘中。我在问题中已经提到过我能够加载保存的文件,所以这并没有什么用处。 - TheComeOnMan
据我所知,它不会将文件保存到磁盘。这是一个由renderImage使用的文件,与renderPlot框架相对。因此,它将直接渲染gganimate,无需进一步操作,但是它使用renderImage进行渲染。 - kt.leap

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接