【问题标题】:Downloading graphs in Shiny在 Shiny 中下载图表
【发布时间】:2016-08-17 11:35:46
【问题描述】:

我正在尝试下载我在 Shiny 中制作的图表,我发现了一篇关于此主题的 Stackoverflow 帖子here。但是,当我从答案运行代码时,一切似乎都可以正常工作,除了“保存”后我无法打开图表。我在保存它们的文件夹中看不到它们,当我尝试从最近的文件中打开它们时,会弹出错误“找不到文件”。

这是我正在使用的代码:

library(shiny)
library(ggplot2)
runApp(list(
#ui
  ui = fluidPage(downloadButton('downloadPlot')),

#server
server = function(input, output) {
   datasetInput <- reactive({
switch(input$dataset,
       "rock" = rock,
       "pressure" = pressure,
       "cars" = cars)
 })

plotInput <- reactive({
  df <- datasetInput()
  p <-ggplot(df, aes_string(x=names(df)[1], y=names(df)[2])) +
  geom_point()
 })
output$downloadPlot <- downloadHandler(
filename = function() { paste(input$dataset, '.png', sep='') },
content = function(file) {
    ggsave(file, plot = plotInput(), device = "png")
}
)
}
))

【问题讨论】:

  • 当我在客户端定义 downloadHandler 中缺少的输入时,它对我来说一切正常:selectInput("dataset", "Choose a dataset:", choices = c("rock", "pressure", "cars"))
  • 我在我的 UI 中将 input$dataset 更改为 input$filename,这是一个 textInput,但它仍然不起作用

标签: r shiny


【解决方案1】:

或者,您可以使用plotly 提供下载可能性,无需进一步配置(下载按钮位于图表的右上角):

library(shiny)
library(plotly)
runApp(list(
  #ui
  ui = fluidPage(selectInput("dataset", "Choose a dataset:", choices = c("rock", "pressure", "cars")),
                 plotlyOutput('plot')),

  #server
  server = function(input, output) {
    datasetInput <- reactive({
      switch(input$dataset,
             "rock" = rock,
             "pressure" = pressure,
             "cars" = cars)
    })

    output$plot <- renderPlotly({
      df <- datasetInput()
      ggplot(df, aes_string(x=names(df)[1], y=names(df)[2])) +
        geom_point()

      ggplotly()
    })

  }
))

【讨论】:

    【解决方案2】:

    我尝试使用 textInput 复制您的代码,这对我来说很好。

    library(shiny)
    library(ggplot2)
    runApp(list(
    
    #ui
     ui = fluidPage(downloadButton('downloadPlot'),
                    textInput("filename", "Choose a dataset:")),
    
    #server
     server = function(input, output) {
      datasetInput <- reactive({
       switch(input$filename,
              "rock" = rock,
              "pressure" = pressure,
              "cars" = cars)
      })
    
      plotInput <- reactive({
       df <- datasetInput()
       p <- ggplot(df, aes_string(x=names(df)[1], y=names(df)[2])) +
            geom_point()
      })
      output$downloadPlot <- downloadHandler(
       filename = function() { paste(input$filename, '.png', sep='') },
       content = function(file) {
         ggsave(file, plot = plotInput(), device = "png")
       }
      )
     }
    ))
    

    【讨论】:

      猜你喜欢
      • 2017-04-01
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 2021-06-22
      • 2018-05-18
      • 1970-01-01
      相关资源
      最近更新 更多