0

I want to display my animated bar plot in R shiny web app. I am getting my animated plot in the Rstudio viewer pane but unfortunately, it is not working in app

CODE:

# LIBRARIES
library(ggplot2)
library(shiny)
library(gganimate)

# LOADING CSV
undergradDATA <- read.csv(file="1-10 Undergraduates.csv", head=TRUE, sep=",")

# UI
ui <- fluidPage (
  mainPanel(
    plotOutput("myplot")
  )
)

# SERVER
server <- function(input, output) {
  output$plot <- renderPlot({
    undergrad_plot <- ggplot(data=undergradDATA , aes(x=HEI, y=Undergrad), height = 461, width = 644) +
      geom_bar(stat='identity', fill="darkolivegreen3", colour="white")
    undergrad_plot + ggtitle("Ranking of Top 10 HEI's w.r.t Undergraduates") +
      theme(
        plot.title = element_text(hjust = 0.5,
                                  colour = "darkolivegreen",
                                  size = 17,
                                  family = "courier"
        ) )
    undergrad_plot + transition_states(Undergrad, wrap = FALSE) +
      shadow_mark() +
      enter_grow() +
      enter_fade()

  })
}

# RUNNING APP
shinyApp(UI, server)
stefan
  • 90,330
  • 6
  • 25
  • 51

1 Answers1

3

Besides some minor flaws in your code (it should be "plot" instead of "myplot" and "ui" instead of "UI" the main issue is that you can't render and output an animated plot via renderPlot and plotOutput. Instead you have to make use of renderImage and imageOutput.

Adapting this answer and making use of some example data created from ggplot2::mpg:

library(ggplot2)
library(shiny)
library(gganimate)
library(dplyr)

## Example data
undergradDATA <- mpg %>%
  count(class, sort = TRUE) %>%
  mutate(class = reorder(class, n)) %>%
  rename(Undergrad = class, HEI = n)

ui <- fluidPage(
  mainPanel(imageOutput("plot"))
)

server <- function(input, output) {
  output$plot <- renderImage(
    {
      undergrad_plot <- ggplot(data = undergradDATA, aes(x = HEI, y = Undergrad), height = 461, width = 644) +
        geom_bar(stat = "identity", fill = "darkolivegreen3", colour = "white")
      undergrad_plot + ggtitle("Ranking of Top 10 HEI's w.r.t Undergraduates") +
        theme(
          plot.title = element_text(
            hjust = 0.5,
            colour = "darkolivegreen",
            size = 17,
            family = "mono"
          )
        )

      anim <- undergrad_plot +
        transition_states(Undergrad, wrap = FALSE) +
        shadow_mark() +
        enter_grow() +
        enter_fade()

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

      # Return a list containing the filename
      list(src = "outfile.gif", contentType = "image/gif")
    },
    deleteFile = TRUE
  )
}

shinyApp(ui, server)

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51