闪亮的下载处理程序不适用于绘图

问题描述 投票:0回答:1

我正在尝试保存在我的闪亮应用程序上创建的绘图,它对于 CSV 文件来说工作得非常好。但是,我无法保存 ggplot2 的绘图。在这种情况下会出现什么问题?

我收到以下错误

在图像中保存 7 x 7 警告:Plotnca1 中的错误:找不到函数“Plotnca1”

  output$Plotnca1<-renderPlot({plot(Plot1<-modnca() %>% 
                                      ggplot()+
                                   geom_line(aes_string(y=input$ycol,x=input$xcol,group=(input$subid)))+
                                   theme_bw())})
  
  output$downloadplot <- downloadHandler(
    filename = function() {
      paste("pk_plot", ".png", sep = "")
    },
    content = function(file) {
      ggsave(file, plot = Plotnca1(), dpi = 300,device="png")
    }
  )
r shinydashboard
1个回答
0
投票

我认为主要问题是

output$Plotncal <- renderPlot({...})
并不像我们想象的那样起作用。我认为,策略是将您的绘图作为响应式,在 renderPlot 调用和下载处理程序中调用该响应式 - 至少这是我过去使用的。

  # Create a reactive object which returns a plot
  plot_ncal_reactive <- shiny::reactive({
    plot <- modnca() %>% 
      ggplot()+
      geom_line(aes_string(y=input$ycol,x=input$xcol,group=(input$subid)))+
      theme_bw())
  
  return(plot)
  })

  # Render the reactive plotting object
  output$Plotnca1 <- shiny::renderPlot(plot_ncal_reactive())

  # Download the reactive object in place of the renderPlot
  output$downloadplot <- downloadHandler(
    filename = function() {
      paste("pk_plot", ".png", sep = "")
    },
    content = function(file) {
      ggsave(file, plot = plot_ncal_reactive(), dpi = 300,device="png")
    }
  )

如果语法略有偏差,则想法应该是正确的。如果没有,reprex 会非常有帮助:)

顺便说一句,可能值得考虑从 aes_string 重构为 aes() 并使用 .data[[input$xcol]], .data[[input$ycol]]

这里包括一个示例,您应该能够复制、粘贴并运行该应用程序以查看其工作原理

  library(shiny)
  library(tidyverse)
  ui <- fluidPage(
    shiny::downloadButton(
      outputId = "plotDownload"
    ),
    shiny::plotOutput(
      outputId = "plotOutput"
    )
  )
  
  server <- function(input, output, session) {
    data <- mtcars
    plot_reactive <- shiny::reactive({
      plot <- mtcars %>%
        ggplot(aes(x= mpg)) +
        geom_histogram()
      
      return(plot)
    })
    
    output$plotOutput <- shiny::renderPlot({plot_reactive()})
    
    output$plotDownload <- output$plotDownload <- downloadHandler(
      filename = function() {
        paste("pk_plot", ".png", sep = "")
      },
      content = function(file) {
        ggsave(file, plot = plot_reactive(), dpi = 300,device="png")
      }
    )
  }
  
  shinyApp(ui, server)
© www.soinside.com 2019 - 2024. All rights reserved.