【问题标题】:Pass image objects through shiny but outside renderPlot通过闪亮但在外部的渲染图传递图像对象
【发布时间】:2020-04-05 23:34:52
【问题描述】:

我有一个闪亮的应用程序,它使用 fileInputmagick 读取用户选择的图像,并将其显示为 ggplot。

library(shiny)
library(magick)
library(ggplot2)

ui <- fluidPage(


   titlePanel(""),


   sidebarLayout(
      sidebarPanel(
        fileInput("current_image", "Choose image file")),


      mainPanel(
        plotOutput("current_image_plot")
      )
   )
)


server <- function(input, output) {

  output$current_image_plot <- renderPlot({
    req(input$current_image)
    myplot <- magick::image_read(input$current_image$datapath)
    myplot <- image_ggplot(myplot)
    return(myplot)
})
}

shinyApp(ui = ui, server = server)

但是,我想将读取图像的逻辑与绘制图像的逻辑分开。我尝试将image_read 放在它自己的observeEvent 中,但这引发了错误The 'image' argument is not a magick image object.

我知道当我在observeEvent 中打印class(myplot) 时,它会返回一个magick-image 对象,那么当我尝试访问active_image 时发生了什么变化?

library(shiny)
library(magick)
library(ggplot2)

ui <- fluidPage(


   titlePanel(""),

   sidebarLayout(
      sidebarPanel(
        fileInput("current_image", "Choose image file")),


      mainPanel(
        plotOutput("current_image_plot")
      )
   )
)


server <- function(input, output) {

  active_image <- observeEvent(input$current_image, {
    req(input$current_image)
    myplot <- magick::image_read(input$current_image$datapath)
    return(myplot)
  })

  output$current_image_plot <- renderPlot({
    req(input$current_image)
    myplot <- image_ggplot(active_image)
    return(myplot)
})
}

shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r shiny shinymodules


    【解决方案1】:

    observeEvent 不返回对象。使用eventReactive instaed,即替换

      active_image <- observeEvent(input$current_image, {
        req(input$current_image)
        myplot <- magick::image_read(input$current_image$datapath)
        return(myplot)
      })
    

      active_image <- eventReactive(input$current_image, {
        req(input$current_image)
        myplot <- magick::image_read(input$current_image$datapath)
        return(myplot)
      })
    

    或更简洁:

      active_image <- eventReactive(input$current_image, {
        req(input$current_image)
        magick::image_read(input$current_image$datapath)
      })
    

    现在,active_image 是一个反应导体,它不是返回的值。你必须做active_image()才能得到返回值:

      output$current_image_plot <- renderPlot({
        req(input$current_image)
        image_ggplot(active_image())
      })
    

    【讨论】:

      猜你喜欢
      • 2016-12-29
      • 1970-01-01
      • 2015-01-11
      • 2019-09-03
      • 2021-06-17
      • 2018-01-25
      • 1970-01-01
      • 2015-09-17
      • 1970-01-01
      相关资源
      最近更新 更多