如何使用R Shiny downloadHandler下载ggplotly图?

托马斯·罗莎

我正在R中制作一个Shiny应用程序。我使用plotly使ggplots交互,因此应用程序中有很多ggplotly图。我希望能够通过界面上的按钮下载每个。

我的下载按钮适用于普通ggplot对象,但不适用于ggplotly对象。一个简单的可复制示例是:

library(shiny)
library(ggplot2)
library(processx) # for orca()
library(plotly)

ui <- fluidPage(
  mainPanel(plotlyOutput("plot1"), downloadButton('download1', 'Download Graph'))
  )

server <- function(input,output){
  make_plot1 <- function(){
    p1 = ggplot(cars, aes(x = speed, y = dist)) + geom_point()
    return(ggplotly(p1))}

  output$plot1 <- renderPlotly({ make_plot1() }) 

  output$download1 <- downloadHandler(
    filename = function() {'plot1.png'},
    content = function(file) {
      # try 1
      png(file)
      print(make_plot1())

      # try 2
      #plotly_IMAGE(make_plot1(), format = "png", out_file = file)

      # try 3
      #orca(make_plot1(), file)

      #try 4
      #export(make_plot1(), file = file)

      dev.off()
      })
  }

shinyApp(ui, server)

我尝试过的某些事情在该代码中已注释掉。

尝试1基于我通常如何在闪亮的应用程序中处理绘图对象

尝试2基于此问题这篇文章

尝试3基于一些密谋性文档

尝试4是基于这个问题

所有这些尝试要么下载空白的.png(尝试1),要么根本下载不了任何东西(尝试2-4)。我怀疑我不太正确地使用下载处理程序。有人对这个工作有建议吗?

编辑:在这种情况下,我需要.png文件,但是此线程上有一些很好的答案,用于下载交互式.html文件。

您是否出于某种原因需要使用下载按钮来完成此操作?如果没有,则在模式栏中有一个自己的按钮,可下载到PNG。

在此处输入图片说明

仪表板取自https://plot.ly/r/dashboard/

在plotly支持论坛(https://community.plot.ly/t/remove-options-from-the-hover-toolbar/130/3)中,您可以config()用来删除其他组件。

make_plot1 <- function() {
  p1 = ggplot(cars, aes(x = speed, y = dist)) + geom_point()
  p1 = ggplotly(p1) %>%
    config(
      modeBarButtonsToRemove = list(
        "zoom2d",
        "pan2d",
        "zoomIn2d",
        "zoomOut2d",
        "autoScale2d",
        "resetScale2d",
        "hoverClosestCartesian",
        "hoverCompareCartesian",
        "sendDataToCloud",
        "toggleHover",
        "resetViews",
        "toggleSpikelines",
        "resetViewMapbox"
      ),
      displaylogo = FALSE
    )
  return(p1)
}

您还可以使用CSS移动模式栏,使其不覆盖图解。

.modebar {
    top: -30px !important;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章