Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Shiny: fast reactive image display

I'm trying to display images in my shiny app reactively. I've successfully done that in the server.R script with:

output$display.image <- renderImage({

    image_file <- paste("www/",input$image.type,".jpeg",sep="")

    return(list(
      src = image_file,
      filetype = "image/jpeg",
      height = 520,
      width = 696
    ))

  }, deleteFile = FALSE)

BUT it's very slow.

However, it is VERY fast to embed one of the images into the ui.R script like so:

tabPanel("Live Images", img(src = "img_type1.jpeg"))

Why is there such a difference? Is there any way to make the reactive images appear faster?

like image 967
maia Avatar asked Apr 14 '15 20:04

maia


1 Answers

Hi you can use conditionalPanel to do this, it embed all your images but only the one which have TRUE to the condition will be displayed :

tabPanel("Live Images", 
     conditionalPanel(condition = "input.image_type == 'img_type1'",
                      img(src = "img_type1.jpeg")
     ),
     conditionalPanel(condition = "input.image_type == 'img_type2'",
                      img(src = "img_type2.jpeg")
     )
)

And change the name of your input from image.type to image_type because . have special meaning in Javascript (as between input and image_type).

If you have a lot of images, you can always do something like that :

tabPanel("Live Images", 
         lapply(X = seq_len(10), FUN = function(i) {
           conditionalPanel(condition = paste0("input.image_type == 'img_type", i, "'"),
                            img(src = paste0("img_type", i, ".jpeg"))
           )
         })
)

For example, with images from this post by tsperry (you can find it on rbloggers too), you can do :

library("shiny")
ui <- fluidPage(
  tabsetPanel(
    tabPanel("Live Images", 
         # 50 images to display
         lapply(X = seq_len(50), FUN = function(i) {
           # condition on the slider value
           conditionalPanel(condition = paste0("input.slider == ", i),
                            # images are on github
                            img(src = paste0("https://raw.githubusercontent.com/pvictor/images/master/",
                                             sprintf("%04d", i), "plot.png"))
           )
         }),
         sliderInput(inputId = "slider", label = "Value", min = 1, max = 50, value = 1, 
                     animate = animationOptions(interval = 100, loop = TRUE))
    )
  )
)

server <- function(input, output) {

}

shinyApp(ui = ui, server = server)
like image 161
Victorp Avatar answered Nov 16 '22 03:11

Victorp