2014-11-05 4 views
8

Я довольно новичок в Shiny (и R) и борюсь с экспортом сюжета, который я делаю в Shiny, в png-файле.Загрузка png из Shiny (R)

Я смотрел на эти две нити, но не мог понять:

Save plots made in a shiny app Shiny downloadHandler doesn't save PNG files

мне удалось создать кнопку загрузки в пользовательском интерфейсе, и сервер, кажется, делает все, что я хочу его делаю, тоже. Когда я нажимаю кнопку загрузки в окне предварительного просмотра, всплывающее окно просит указать местоположение и имя файла, но файл не сохраняется. Когда я делаю то же самое в окне браузера, создается файл png, но он пуст.

Любое понимание очень ценится!

ui.R

library(shiny) 

shinyUI(fluidPage(
    titlePanel("This is a scatterplot"), 

    sidebarLayout(
    sidebarPanel(

     fileInput('datafile', 'Choose CSV file', 
       accept=c('text/csv', 'text/comma-separated-values,text/plain')), 

     uiOutput("varselect1"), 

     uiOutput("varselect2"), 

     downloadButton('downloadPlot', 'Download Plot') 

    ), 

    mainPanel(   
      h4("Here is your scatterplot"), 
      plotOutput("plot1") 
       ) 
    )) 
) 

server.R

library(foreign) 

shinyServer(function(session,input, output) { 

    DataInput <- reactive({ 
     infile <- input$datafile 
     if (is.null(infile)) { 

     return(NULL) 
     } 
     read.csv(infile$datapath) 
    }) 


    output$varselect1 <- renderUI({ 

     if (identical(DataInput(), '') || identical(DataInput(),data.frame())) return(NULL) 

     cols <- names(DataInput()) 
     selectInput("var1", "Select a variable:",choices=c("---",cols[3:length(cols)]), selected=("---")) 

    }) 

    output$varselect2 <- renderUI({ 

     if (identical(DataInput(), '') || identical(DataInput(),data.frame())) return(NULL) 

     cols <- names(DataInput()) 
     selectInput("var2", "Select a variable:",choices=c("---",cols[3:length(cols)]), selected=("---")) 

    }) 



    plotInput <- reactive({ 

     a <- which(names(DataInput())==input$var1) 
     x_lab <- as.numeric(DataInput()[,a]) 


     b <- which(names(DataInput())==input$var2) 
     y_lab <- as.numeric(DataInput()[,b])  

     main.text <- paste("Scatterplot of the variables",colnames(DataInput())[a],"and", colnames(DataInput())[b],sep = " ", collapse = NULL) 

     plot(x_lab, y_lab, main=main.text, xlab=colnames(DataInput())[a], ylab=colnames(DataInput())[b], xlim=c(min(x_lab),max(x_lab)*1.05), ylim=c(min(y_lab), max(y_lab)*1.05)) 

     observations <- DataInput()[,1] 

     text(x_lab, y_lab, labels=observations, pos=3) 


    }) 

    output$plot1 <- renderPlot({ 
      print(plotInput()) 
    }) 


    output$downloadPlot <- downloadHandler(
     filename = "Shinyplot.png", 
     content = function(file) { 
     png(file) 
     print(plotInput()) 
     dev.off() 
     })  

    }) 

ответ

12

Обойти этот странный сценарий обсуждался на shiny-discuss google group. То, что вы можете сделать, это просто изменить ваш реактивный оператор plotInput в обычную функцию. Не знаю, почему downloadHandler не играет хорошо с реактивными объектами.

# change 
plotInput <- reactive({...}) 

# into this 
plotInput <- function(){...} 

Вы также можете удалить оператор печати в downloadHandler вызова:

output$downloadPlot <- downloadHandler(
     filename = "Shinyplot.png", 
     content = function(file) { 
     png(file) 
     plotInput() 
     dev.off() 
     })  
+0

Это фантастика. Провел последние несколько часов, пытаясь загрузить коллекцию реактивных сюжетов, и не мог понять, что происходит не так. Мой мозг слишком обжарен, чтобы понять, есть ли какие-либо негативы для перехода от «реактивного» к «функции», но, похоже, он хорошо работает – Adrian

Смежные вопросы