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

时间:2016-02-16 01:05:51

标签: shiny gif gganimate

我可以将已保存的文件作为图片加载,但无法使用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 个答案:

答案 0 :(得分:5)

我正在处理同样的问题,只发现了你的问题而没有答案......但是你用它的方式提醒我renderPlot很挑剔:

  

它不会将任何图像文件发送到浏览器 - 图像必须由使用R的图形输出设备系统的代码生成。 renderPlot()无法发送其他创建图像的方法......在这些情况下,解决方案是renderImage()函数。 source

修改该文章中的代码可提供以下内容:

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)

答案 1 :(得分:3)

现在有了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)