单击一个动作按钮,并将ggplot另存为pdf

时间:2019-06-20 15:44:26

标签: pdf ggplot2 shiny download save

我试图在按下downloadButton之后将动态输出的ggplot下载/保存为pdf。

我尝试了多种方法来从多个在线来源进行此操作,但每次均未成功。我附上了相关代码,希望有人可以帮助我创建适当的功能“ downloadPlot”。

ui <- ......
      .
      .
downloadButton('downloadPlot','Download Image'),
      .
      .
server <- function(input,output,session){
      .                                           
      .
# DP Box Plots 
  output$one <- renderPlot({
    if(input$layer == "State Specific"){
      validate(
        need(input$ES, "Please select a state to access the box plots."))
      }
    else if(input$layer == "Niche Specific"){
      validate(
        need(input$niche, "Please select a niche to access the box plot.")
      )
    }
    else if(input$layer == "State/Niche Specific"){
      validate(
        need(input$SoN, "Please select a state. ")
      )
      validate(
        need(input$NoS, "Please select a niche. ")
      )
    }
    else if(input$layer == "New/Renewal Specific"){
      validate(
        need(input$NR, "Please select new or renewal to view box plots.")
      )
    }

    ggplot(Dataset(), aes(x= reorder(Niche_Groups, 
Discretionary_Price_Relativity, FUN = median), y = 
Discretionary_Price_Relativity)) + geom_boxplot() + coord_flip() + 
ggtitle(paste("Discretionary Pricing - ",titlename())) + theme(plot.title = 
element_text(hjust = 0.5)) +
       ylab("Ratio to Technical") + xlab("Niche Groups")
   })

1 个答案:

答案 0 :(得分:1)

server <- function(input,output,session){
  .                                           
  .

  theplot <- reactive({
    if(input$layer == "State Specific"){
      validate(
        need(input$ES, "Please select a state to access the box plots."))
    }
    else if(input$layer == "Niche Specific"){
      validate(
        need(input$niche, "Please select a niche to access the box plot.")
      )
    }
    else if(input$layer == "State/Niche Specific"){
      validate(
        need(input$SoN, "Please select a state. ")
      )
      validate(
        need(input$NoS, "Please select a niche. ")
      )
    }
    else if(input$layer == "New/Renewal Specific"){
      validate(
        need(input$NR, "Please select new or renewal to view box plots.")
      )
    }

    ggplot(Dataset(), aes(x= reorder(Niche_Groups, 
                                     Discretionary_Price_Relativity, FUN = median), y = 
                            Discretionary_Price_Relativity)) + geom_boxplot() + coord_flip() + 
      ggtitle(paste("Discretionary Pricing - ",titlename())) + theme(plot.title = 
                                                                       element_text(hjust = 0.5)) +
      ylab("Ratio to Technical") + xlab("Niche Groups")    
  })

  output$one <- renderPlot({
    theplot()
  })

  output$downloadPlot <- downloadHandler(
    filename = "theplot.pdf",
    content = function(file){
      ggsave(file, theplot())
    }
  )