Use reactive expressions in renderPlot and download handler
我在 shiny 应用程序的 renderPlot()
和 downloadHandler()
中使用响应式(Reactive)表达式时遇到了问题。我想这样做是为了减少代码中的维护和冗余。
上述问题适用于“普通”绘图函数,如 plot、hist 等。 在我的应用程序中,我使用了一个创建绘图的更复杂的函数。我已经创建了它的简化版本
helpfunc <- function(mean, sd) {
hist(rnorm(1000, mean, sd))
lines(1:10)
}
如果您现在在您的 shiny app
中使用此函数,则在从中创建响应式(Reactive)表达式时它不起作用。既不使用 plot()
也不使用响应式(Reactive)表达式本身。
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()
}
)
}
最佳答案
lines
基本上是对 plot.xy
的调用。除了这次您无法分配 lines
的输出外,您遇到了与之前相同的问题。和以前一样,您可以分配 hist
函数的输出。
helpfunc <- function(mean, sd) {
hist = hist(rnorm(1000, mean, sd))
myLines = function(){lines(1:10)}
myLines()
list(hist = hist, lines = myLines)
}
mwe2 <- 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) {
myHist <- .hist()
jpeg(file, quality = 100, width = 800, height = 800)
plot(myHist$hist)
myHist$lines()
dev.off()
}
)
}
)
runApp(app)
}
关于r - 在使用自己的函数时在 renderPlot 和下载处理程序中使用 react 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24162675/