在Shiny中下载图表

时间:2016-08-17 11:35:47

标签: r shiny

我正在尝试下载我在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")
}
)
}
))

2 个答案:

答案 0 :(得分:1)

我尝试使用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")
   }
  )
 }
))

答案 1 :(得分: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()
    })

  }
))