R Shiny renderImage() 无法识别对象 'input'

R Shiny renderImage() does not recognize object 'input'

为什么 renderImage() 无法识别下面代码示例中的 input

library(d3heatmap)
library(shiny)
library(ggplot2)


    ui <- fluidPage(
      h1("A heatmap demo"),
      selectInput("palette", "Palette", c("YlOrRd", "RdYlBu", "Greens", "Blues")),
      checkboxInput("cluster", "Apply clustering"),
      downloadButton('downloadPlot', 'Download Heatmap'),
      d3heatmapOutput("heatmap")
)

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

      output$heatmap <- renderD3heatmap({
        d3heatmap(
          scale(mtcars),
          colors = input$palette,
          dendrogram = if (input$cluster) "both" else "none"
) })

    output$downloadPlot <- renderImage(
        d3heatmap(scale(mtcars), colors = input$palette, dendrogram = if (input$cluster) "both" else "none"), 
        env = parent.frame(), 
        quoted = FALSE, 
        deleteFile = FALSE
        )

    }

shinyApp(ui = ui, server = server)

这是我的错误:

Error in match.arg(dendrogram) : object 'input' not found

当我删除 dendrogram = if (input$cluster) "both" else "none" 行时,我再次收到有关 input 的以下错误:

Error in toPaletteFunc(pal) : object 'input' not found

找不到对象 input 似乎有点违反直觉,因为我在楼上明确定义了它:server <- function(input, output, session).

我已经检查了生成类似错误消息的现有 Stack Overflow 帖子(例如,)。

上面的代码示例的灵感来自:https://cran.r-project.org/web/packages/d3heatmap/d3heatmap.pdf

d3heatmap() 生成 htmlwidgets class 对象。我们可以使用 htmlwidgets 包中的 saveWidget() 函数来保存绘图。

library(d3heatmap)
library(shiny)
library(htmlwidgets)

ui <- fluidPage(
    h1("A heatmap demo"),
    selectInput("palette", "Palette", c("YlOrRd", "RdYlBu", "Greens", "Blues")),
    checkboxInput("cluster", "Apply clustering"),
    downloadButton('download', 'Download Heatmap'),
    d3heatmapOutput("heatmap")
)
server <- function(input, output, session) {
    plot <- reactive({
        d3heatmap(
            scale(mtcars),
            colors = input$palette,
            dendrogram = if (input$cluster) "both" else "none"
        )
    })
    output$heatmap <- renderD3heatmap({
        plot()
    })
    output$download <- downloadHandler(
        filename = function() {
            paste0("d3heatmap-", tolower(input$palette), ".html")
        },
        content = function(file) {
            saveWidget(plot(), file)
        }
    )
}

shinyApp(ui = ui, server = server)

如果您需要将图另存为 png,请参阅此讨论:https://github.com/ramnathv/htmlwidgets/issues/95. In short: now htmlwidgets does not support export plots as png or svg. You can see exportwidget and webshot packages as workground。