Use reactive expressions in renderPlot and download handler
I have had problems by using reactive expressions both in renderPlot()
and in downloadHandler()
in shiny applications. I want to do this to reduce maintenance and redundancy in my code.
The above issue works with "normal" plot functions like plot, hist, etc. In my application I'm using a more complex function which creates a plot. I have created a simplified version of it
helpfunc <- function(mean, sd) {
hist(rnorm(1000, mean, sd))
lines(1:10)
}
If you use this function now in your shiny app
, it does not work when creating a reactive expression out of it. Neither by using plot()
nor by using the reactive expression itself.
mwe <- function() {
app = list(
ui = bootstrapPage(
fluidPage(
sidebarPanel(
sliderInput("mean", "choose mean", -10, 10, 1),
sliderInput("sd", "choose sd", 0, 5, 1)),
mainPanel(
plotOutput("hist"),
downloadButton("histDownload")
)
)
),
server = function(input, output) {
output$hist <- renderPlot(.hist())
.hist <- reactive(helpfunc(input$mean, input$sd))
output$histDownload <- downloadHandler(
filename = function() {
paste("hist.jpg")
},
content = function(file) {
jpeg(file, quality = 100, width = 800, height = 800)
.hist() ## works not for plot(.hist()) either
dev.off()
}
)
}