I'm making a Shiny app that involves making plots from a function from a bioinformatics package that uses base R graphics. I'm building the Shiny app in RStudio Server. Since the plot can only be made with that function in that package, using ggplot2 or highcharter instead is not an option. I have no problem with saving plots made by ggplot2, but got into trouble when trying to save plots made with base R graphics. I used the answer in Downloadhander (save plot) for basic plot in shiny, but when I clicked the download button, I got "404 not found" and download was not initiated, even though that plot displayed properly within the Shiny app. Here's a modified version of RStudio's default Faithful Geyser app that can reproduce this problem:
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30),
downloadButton("download", "Download plot")
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
p <- reactive({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
output$distPlot <- renderPlot(p())
output$download <- downloadHandler("foo.png",
content = function(file) {
png(file = file)
p()
dev.off()
})
}
# Run the application
shinyApp(ui = ui, server = server)
It seems that the problem is related to
png(file = file)
p()
dev.off()
not working within Shiny, since when I tried to save ggplot this way, it also gave "404 not found", while ggsave
worked fine to download ggplot (though not base R plots) inside the Shiny app. Outside Shiny, the base R way to save plots works properly.