【问题标题】:Saving user generated ggplot from Shiny App从 Shiny App 保存用户生成的 ggplot
【发布时间】:2021-04-17 20:51:35
【问题描述】:

我正在尝试使用 ggplot 创建一个闪亮的 Web 应用程序,并包含一个下载生成的绘图的功能。这里分别是我的 UI 和服务器文件。

服务器

shinyServer(function(input, output, session) {
  
  vals <- reactiveValues()
  
    output$Plot <- renderPlot({
      gg <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
      vals$gg <- gg
      
      print(gg)
    }, height = function() {
      session$clientData$output_BehPlot_width
    } )
    
    # downloadHandler contains 2 arguments as functions, namely filename, content
    output$down <- downloadHandler(
      filename =  function() {
        paste("behavior", input$var3, sep=".")
      },
      # content is a function with argument file. content writes the plot to the device
      content = function(filename) {
        if(input$var3 == "png"){
          png(filename) # open the png device
          #ggsave(vals$gg)
          print(vals$gg) # for GGPLOT
          dev.off()  # turn the device off
          }
        else {
          #ggsave(vals$gg)
          pdf(filename) # open the pdf device
        print(vals$gg) # for GGPLOT
        dev.off()  # turn the device off
        }
      } 
    )


    
})

用户界面

shinyUI(fluidPage(
  
  # Application title
  titlePanel("TEST SHINY"),
  
  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
      radioButtons(inputId = "var3", label = "Select the file type", choices = list("png", "pdf")),
      
      downloadButton("downloadPlot", "Download")
    ),
    
    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("Plot", height="auto", width = "auto")
    )
  )
))

这是根据之前几个 Stack Overflow 线程和 Github 要点的咨询而构建的。 (比如这个:R Shiny saving reactive ggplots

当我在 R 控制台和浏览器的测试会话中运行下载功能时,结果是一个不打印绘图的 HTML 文件。有什么我遗漏的吗?

谢谢!

【问题讨论】:

  • 应该是downloadButton("down", "Download") 而不是downloadPlot。此外,它应该是 session$clientData$output_Plot_width 而不是 output_BehPlot_width

标签: r ggplot2 shiny


【解决方案1】:

您可以使用plotly 包来执行此操作。作为奖励,您的情节将是互动的。要保存绘图,请查看 plotly 绘制的右上角图标菜单。

library(plotly)

# use plotlyOutput instead of plotOutput in UI
# use renderPlotly instead of renderPlot in server
# wrap your ggplot in ggplotly

output$Plot <- renderPlotly(
  ggplotly(ggplot(mtcars, aes(mpg, wt)) + geom_point())
)

注意:在您的代码中,您不必将绘图放在反应变量中,因为它不会触发观察者或渲染器。一个简单的变量就可以完成这项工作。

【讨论】:

    猜你喜欢
    • 2015-06-24
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多