chartJSRadar скачать обработчик создания пустого png - PullRequest
0 голосов
/ 02 мая 2020

Я хотел бы создать кнопку загрузки в моем блестящем приложении, чтобы загрузить реактивный график, созданный с помощью chartJSRadar. Я не могу решить эту проблему! Так как я прошел через задокументированную проблему на inte rnet, я не смог ее решить, постоянно получая пустой png. Как и предполагалось ( Сохранить графики, сделанные в блестящем приложении ), https://groups.google.com/forum/#! Msg / ceramic-обсуждение / u7gwXc8_vyY / IZK_o7b7I8gJ
Я построил функцию ... Итак, мой код пример кода:

ui.R:

library(radarchart)

shinyUI(pageWithSidebar(
  headerPanel('Radarchart Shiny Example'),
  sidebarPanel(
    checkboxGroupInput('selectedPeople', 'Who to include', 
                       names(radarchart::skills)[-1], selected="Rich")
  ),
  mainPanel(
    chartJSRadarOutput("plot1", width = "450", height = "300"), width = 7,
  radioButtons(inputId = "var3", label = "Select the file type", choices = list("png", "pdf")),
  downloadButton('downloadPlot', 'Download Plot')
  )
))

server.R


library(radarchart)

shinyServer(function(input, output) {
  output$plot1 <- renderChartJSRadar({

    chartJSRadar(skills[, c("Label", input$selectedPeople)], 
                 maxScale = 10, showToolTipLabel=TRUE)
  })

  plot2 <- function(){
    chartJSRadar(skills[, c("Label", input$selectedPeople)], 
                 maxScale = 10, showToolTipLabel=TRUE)
  }

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

Ответы [ 2 ]

0 голосов
/ 03 мая 2020

Вот способ JavaScript, который должен быть быстрее, чем webshot, я думаю.

library(shiny)
library(radarchart)
library(htmlwidgets) # to use the 'onRender' function

js <- c(
  "function(el, x){",
  "  $('#downloadPlot').on('click', function(){",
  "    // Clone the chart to add a background color.",
  "    var cloneCanvas = document.createElement('canvas');",
  "    cloneCanvas.width = el.width;",
  "    cloneCanvas.height = el.height;",
  "    var ctx = cloneCanvas.getContext('2d');",
  "    ctx.fillStyle = '#FFFFFF';",
  "    ctx.fillRect(0, 0, el.width, el.height);",
  "    ctx.drawImage(el, 0, 0);",
  "    // Download.",
  "    const a = document.createElement('a');",
  "    document.body.append(a);",
  "    a.download = 'radarchart.png';",
  "    a.href = cloneCanvas.toDataURL('image/png');",
  "    a.click();",
  "    a.remove();",
  "  });",
  "}"
)

ui <- pageWithSidebar(
  headerPanel('Radarchart Shiny Example'),
  sidebarPanel(
    checkboxGroupInput('selectedPeople', 'Who to include', 
                       names(radarchart::skills)[-1], selected="Rich"),
    actionButton('downloadPlot', 'Download Plot')
  ),
  mainPanel(
    chartJSRadarOutput("plot1", width = "450", height = "300"), width = 7
  )
)

server <- function(input, output) {
  output$plot1 <- renderChartJSRadar({
    chartJSRadar(skills[, c("Label", input$selectedPeople)], 
                 maxScale = 10, showToolTipLabel=TRUE) %>% 
      onRender(js)
  })
}

shinyApp(ui, server)

Экспортируется только в png. Используйте webshot для экспорта в pdf.


РЕДАКТИРОВАТЬ

library(shiny)
library(radarchart)

js <- paste0(c(
  "$(document).ready(function(){",
  "  $('#downloadPlot').on('click', function(){",
  "    var el = document.getElementById('plot1');",
  "    // Clone the chart to add a background color.",
  "    var cloneCanvas = document.createElement('canvas');",
  "    cloneCanvas.width = el.width;",
  "    cloneCanvas.height = el.height;",
  "    var ctx = cloneCanvas.getContext('2d');",
  "    ctx.fillStyle = '#FFFFFF';",
  "    ctx.fillRect(0, 0, el.width, el.height);",
  "    ctx.drawImage(el, 0, 0);",
  "    // Download.",
  "    const a = document.createElement('a');",
  "    document.body.append(a);",
  "    a.download = 'radarchart.png';",
  "    a.href = cloneCanvas.toDataURL('image/png');",
  "    a.click();",
  "    a.remove();",
  "    cloneCanvas.remove();",
  "  });",
  "});"
), collapse = "\n")

ui <- pageWithSidebar(
  headerPanel('Radarchart Shiny Example'),
  sidebarPanel(
    checkboxGroupInput('selectedPeople', 'Who to include', 
                       names(radarchart::skills)[-1], selected="Rich"),
    actionButton('downloadPlot', 'Download Plot')
  ),
  mainPanel(
    tags$head(tags$script(HTML(js))),
    chartJSRadarOutput("plot1", width = "450", height = "300"), width = 7
  )
)

server <- function(input, output) {
  output$plot1 <- renderChartJSRadar({
    chartJSRadar(skills[, c("Label", input$selectedPeople)], 
                 maxScale = 10, showToolTipLabel=TRUE) 
  })
}

shinyApp(ui, server)
0 голосов
/ 02 мая 2020

chartJSRadar возвращает htmlWidget. Чтобы сохранить, попробуйте использовать saveWidget, а затем webshot временного файла html. Добавьте webshot library:

library(webshot)

и попробуйте заменить это на downloadHandler в вашей функции server:

output$downloadPlot <- downloadHandler(
  filename = "Shinyplot.png",
  content = function(file) {
    saveWidget(plot2(), "temp.html", selfcontained = TRUE)
    webshot("temp.html", file = file)
  }
) 
...