简体   繁体   English

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

[英]How to download a ggplotly plot with R Shiny downloadHandler?

I'm making a Shiny app in R. I use plotly to make my ggplots interactive, thus I have lots of ggplotly plots in the app. 我正在R中制作一个Shiny应用程序。我使用plotly使ggplots交互,因此应用程序中有很多ggplotly图。 I would like to be able to download each one through a button on the interface. 我希望能够通过界面上的按钮下载每个。

My download button works for normal ggplot objects but not for ggplotly objects. 我的下载按钮适用于普通ggplot对象,但不适用于ggplotly对象。 A simple reproducible example would be: 一个简单的可复制示例为:

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)

Some things I've tried are commented out in that code. 我尝试过的某些事情在该代码中已注释掉。

Try 1 is based on how I would normally handle plot objects in a shiny app 尝试1是基于我通常如何在闪亮的应用程序中处理绘图对象

Try 2 is based on this question and this post 尝试2基于此问题这篇文章

Try 3 is based on some plotly documentation 尝试3基于一些密谋性文档

Try 4 is based on this question 尝试4是基于这个问题

All of these attempts either download a blank .png (try 1) or simply fail to download anything (tries 2-4). 所有这些尝试要么下载空白的.png(尝试1),要么根本下载不了任何东西(尝试2-4)。 I suspect I'm not quite using the download Handler correctly. 我怀疑我不太正确地使用下载处理程序。 Anybody have suggestions for getting this working? 有人对这个工作有建议吗?

EDIT: For this case I want .png files, but there are some good answers on this thread for downloading interactive .html files. 编辑:在这种情况下,我需要.png文件,但是此线程上有一些很好的答案,用于下载交互式.html文件。

Do you need to accomplish this with a download button for some reason? 您是否出于某种原因需要使用下载按钮来完成此操作? If not, plotly has its own button in the modebar that downloads to a PNG. 如果没有,则在模式栏中有一个自己的按钮,可下载到PNG。

在此处输入图片说明

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

From the plotly support forum ( https://community.plot.ly/t/remove-options-from-the-hover-toolbar/130/3 ), you can use config() to remove the other components. 在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)
}

You can also move the modebar so that it doesn't cover the plot, using CSS. 您还可以使用CSS移动模式栏,使其不覆盖图解。

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

Another way would be to use htmlwidgets to save the file as an interactive html, in case that is preferable to a png. 另一种方法是使用htmlwidgets将文件另存为交互式html,以防它比png更好。

To turn this html into a static graphic, a further workaround - if you for some reason do not want to use plotly's printing function at all - would be to save a png with webshot (which requires phantomjs). 要将此html转换为静态图形,进一步的解决方法-如果出于某种原因根本不想使用plotly的打印功能-将使用webshot保存png(这需要phantomjs)。 See code below. 请参见下面的代码。

library("shiny")
library("ggplot2")
library("data.table")
library("plotly")
library("htmlwidgets")
library("webshot")


shinyApp(

  ui = fluidPage(

    mainPanel(plotlyOutput("plot1"),
              downloadButton('download1', 'Download Graph'))
  ),

  server = function(input, output) {

    inputPlot1 <- reactive({
      p1 = ggplot(cars, aes(x = speed, y = dist)) + geom_point()
      ggplotly(p1)
    })

    output$plot1 <- renderPlotly({
      print(inputPlot1())
    })

    output$download1 <- downloadHandler(
      filename = function() {'plot1.html'},
      content = function(file) {

      htmlwidgets::saveWidget(as_widget(inputPlot1()), file)

        # Alternative using webshot with phantomjs
        # saveWidget(as_widget(inputPlot1()), "temp.html", selfcontained = FALSE)
        # webshot(url = "temp.html", file)

      }
    )

  }

) # closes shinyApp

Following your comment to Wil's answer, you can remove the undesired buttons in the modebar as follows: 在对Wil的答案发表评论之后,您可以按如下所示删除模式栏中不需要的按钮:

library(plotly)

x <- c(1:15)
y <- c(1:15)
xy <- as.data.frame(cbind(x,y))
example <- ggplot(data = xy,aes(x = x,y = y)) + geom_line()

ggplotly(example) %>% 
  config(displaylogo = FALSE,
         collaborate = FALSE,
         modeBarButtonsToRemove = list(
           'sendDataToCloud',
           'autoScale2d',
           'resetScale2d',
           'hoverClosestCartesian',
           'hoverCompareCartesian',
           'zoom2d', 
           'pan2d',
           'select2d',
           'lasso2d',
           'zoomIn2d', 
           'zoomOut2d',
           'toggleSpikelines'
         )
  )

References: 参考文献:

如果您希望下载具有交互功能的ggplotly图,请尝试以下方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM