2

我正在尝试为我的直方图创建一个下载按钮。我的下载按钮可见,但似乎无法正确下载。它总是下载 .htm 文件而不是 .png 文件。我在我的 server.R 中使用 ggsave 命令。我尝试使用更传统的方法,但这似乎也不起作用。

library(shiny)
library(plyr)
library(ggplot2)

shinyUI(fluidPage(
  headerPanel(title = "Test"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("input.a", "A", min = 0, max = 100, value = 50),
      sliderInput("input.b", "B", min = 0, max = 100, value = 50),
      sliderInput("input.c", "C", min = 0, max = 100, value = 50)
    ),

    mainPanel(

      tabsetPanel( type = "tabs", #Open panel
                   tabPanel("Distributions",plotOutput("hist.plot")),
                   downloadButton('downloadhist', 'Download Plot'))

) # close mainPanel
) # close sidebarLayout
) # close fluidPage
) # close shinyUI

shinyServer(function(input,output){ # open shiny server

    #output$hist.plot = renderPlot({ # open renderPlot
    make.hist.plot = reactive({

    a = runif(1000,1,(input$input.a))
    b = runif(1000,1,(input$input.b))
    c = runif(1000,1,(input$input.c))

    amount = c(a,b,c)

    cat = c(rep("a",1000), rep("b",1000), rep("c",1000))

    hist.data = data.frame(amount,cat)
    names(hist.data) = c("amount","cat")

    hist.data$cat = factor(hist.data$cat, levels = c("a","b","c"))
    pricedata = ddply(hist.data, c("cat"), summarize, avg = mean(amount), minus.stdev = mean(amount)-sd(amount),
                      plus.stdev = mean(amount) + sd(amount))
    pricedata = pricedata[order(pricedata$avg),]


    ggplot(hist.data, aes(x=amount, fill = cat))+
      geom_histogram(color="white", alpha = .8, position = 'identity', binwidth = 5)+
      theme_test()+
      geom_vline(aes(xintercept = avg), data = pricedata, color = "black", size = 1)+


      geom_vline(aes(xintercept = minus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+


      geom_vline(aes(xintercept = plus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+


      facet_grid(cat ~., scales = "free")+
      scale_y_continuous(expand = c(0,0),name = "Count")+
      scale_x_continuous(labels = scales::dollar, name="\nAmount", limits = c(0,100))

  }) #close renderPlot

   output$hist.plot = renderPlot({
    print(make.hist.plot())
   })

    output$downloadhist = downloadHandler(
      filename = function() { "hist.png" },
      content = function(file) {
        ggsave(file, plot = make.hist.plot(), device = "png")}
    )

}) # close shinyServer



4

1 回答 1

2

这似乎是一个范围问题。如果您将下载按钮放在侧边栏面板中,如果您删除了tabsetPanel,或者如果您将下载按钮放在同一个tabPanel. 最后的解决方案如下所示:

mainPanel(
  tabsetPanel( type = "tabs", #Open panel
    tabPanel("Distributions",
      plotOutput("hist.plot"),
      downloadButton('downloadhist', 'Download Plot')
    )
  )
) # close mainPanel
于 2020-06-03T03:53:58.493 回答