【发布时间】:2021-04-17 20:51:35
【问题描述】:
我正在尝试使用 ggplot 创建一个闪亮的 Web 应用程序,并包含一个下载生成的绘图的功能。这里分别是我的 UI 和服务器文件。
服务器
shinyServer(function(input, output, session) {
vals <- reactiveValues()
output$Plot <- renderPlot({
gg <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
vals$gg <- gg
print(gg)
}, height = function() {
session$clientData$output_BehPlot_width
} )
# downloadHandler contains 2 arguments as functions, namely filename, content
output$down <- downloadHandler(
filename = function() {
paste("behavior", input$var3, sep=".")
},
# content is a function with argument file. content writes the plot to the device
content = function(filename) {
if(input$var3 == "png"){
png(filename) # open the png device
#ggsave(vals$gg)
print(vals$gg) # for GGPLOT
dev.off() # turn the device off
}
else {
#ggsave(vals$gg)
pdf(filename) # open the pdf device
print(vals$gg) # for GGPLOT
dev.off() # turn the device off
}
}
)
})
用户界面
shinyUI(fluidPage(
# Application title
titlePanel("TEST SHINY"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
radioButtons(inputId = "var3", label = "Select the file type", choices = list("png", "pdf")),
downloadButton("downloadPlot", "Download")
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("Plot", height="auto", width = "auto")
)
)
))
这是根据之前几个 Stack Overflow 线程和 Github 要点的咨询而构建的。 (比如这个:R Shiny saving reactive ggplots)
当我在 R 控制台和浏览器的测试会话中运行下载功能时,结果是一个不打印绘图的 HTML 文件。有什么我遗漏的吗?
谢谢!
【问题讨论】:
-
应该是
downloadButton("down", "Download")而不是downloadPlot。此外,它应该是session$clientData$output_Plot_width而不是output_BehPlot_width。