如何显示在Shiny本地存储的多张图片(png)

时间:2018-11-20 05:22:07

标签: r image shiny

我尝试过在网上大量搜索类似的问题,但找不到适合我的情况的问题。我对Shiny陌生,所以希望大家能帮助我。下面是我所拥有的一种代码形式。我在本地拉一些图像时遇到麻烦。在用户界面中,您可以在下拉菜单中看到我可以选择多个县并将其合并的原因。在我的文件夹中,我有许多以这种通用格式标题的png文件:“ CountyX reasonY .png”(文件扩展名前有一个空格)。

我想做的是能够在一个网格中渲染多张图片,这样我就可以比较县和原因的组合(例如,在2x2网格中查看County2原因1和County1原因3以及County2原因3和County4原因2(如果为3x4我有12等)。为了简化起见,我在此处上传了一些png文件进行实验:PNG 1PNG 2PNG 3PNG 4

我尝试过的output $ plots仅用于显示一张图像。

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  titlePanel("Compare"),
  sidebarLayout(
    sidebarPanel(
      pickerInput(inputId = "countyInput", label = "Filter county",
                  choices = c("County1", "County2", "County3", "County4", "County5"),
                  options = list(`actions-box` = TRUE,size = 10, `selected-text-format` = "count > 9"),
                  multiple = TRUE),
      checkboxGroupInput(inputId = "reasonInput", label = "Filter reason",
                         choices = c("reason1", "reason2", "reason3"))
    ),
    mainPanel(
      plotOutput("plot")
    )
  )
)

server <- function(input, output, session) {

  output$plot <- renderImage({
    filename <- normalizePath(file.path("<local path name to png files>", paste(input$countyInput, " ", input$reasonInput, " .png", sep = "")))
    list(src = filename)  
    }, deleteFile = FALSE)

}

shinyApp(ui = ui, server = server)

感谢您的所有帮助。

1 个答案:

答案 0 :(得分:3)

使用gridgridExtrapng,您可以将png渲染到一个“图”中。

library(shiny)
library(shinyWidgets)
library(gridExtra)
library(png)
library(grid)

ui <- fluidPage(
  titlePanel("Compare"),
  sidebarLayout(
    sidebarPanel(
      pickerInput(inputId = "countyInput", label = "Filter county",
                  choices = c("County1", "County2", "County3", "County4", "County5"),
                  options = list(`actions-box` = TRUE,size = 10, `selected-text-format` = "count > 9"),
                  multiple = TRUE),
      checkboxGroupInput(inputId = "reasonInput", label = "Filter reason",
                         choices = c("reason1", "reason2", "reason3"))
    ),
    mainPanel(
      plotOutput("plot")
    )
  )
)

server <- function(input, output, session) {

  output$plot <- renderPlot({
    filename <- normalizePath(file.path("<path>", paste0(input$countyInput, " ", input$reasonInput, ".png", sep = ""))) # you had one extra space before .png
    filename <- filename[file.exists(filename)]
    pngs = lapply(filename, readPNG)
    asGrobs = lapply(pngs, rasterGrob)
    p <- grid.arrange(grobs=asGrobs, nrow = 1)
    }, width = 1000)
}

shinyApp(ui = ui, server = server)

对于不完整的文件名,您当然需要一些错误处理。此外,您可以使用length(filename)作为nrowncol的条件来获取网格中所需的像元数。