我在下载 Shiny 中 downloadHandler() 函数中使用 grid.draw() 创建的绘图时遇到问题。这是我想要实现的目标的可重现示例:
library(gtable)
library(ggplot2)
ui <- shinyUI(fluidPage(
titlePanel("Test app"),
fluidRow(
column(4,
wellPanel(
downloadButton('download',label="Download plot as png")
)
),
column(8,
plotOutput("plot")
)
)
))
server <- function(input,output){
plotting<- reactive({
data1=data.frame(x=rnorm(50),y=rnorm(50))
data2=data.frame(x=rexp(50),y=rexp(50))
plot1=ggplot(data1,aes(x,y))+geom_point()
plot2=ggplot(data2,aes(x,y))+geom_point()
gb1=ggplot_build(plot1)
gb2=ggplot_build(plot2)
gA <- ggplot_gtable(gb1)
gB <- ggplot_gtable(gb2)
both <- gtable:::rbind_gtable(gA, gB, "last")
return(both)
})
output$plot <- renderPlot({
grid.newpage()
grid.draw(plotting())
})
output$download <- downloadHandler(
filename <- "shinytestplot.png",
content <- function(file=NULL){
png(filename)
grid.newpage()
grid.draw(plotting())
dev.off()
}
)
}
shinyApp(server=server,ui=ui)
当我按“下载为 png”时,这会显示在控制台中:
Error opening file: 2
Error reading: 9
在控制台中,此代码运行良好并且绘图按预期保存:
data1=data.frame(x=rnorm(50),y=rnorm(50))
data2=data.frame(x=rexp(50),y=rexp(50))
plot1=ggplot(data1,aes(x,y))+geom_point()
plot2=ggplot(data2,aes(x,y))+geom_point()
gb1=ggplot_build(plot1)
gb2=ggplot_build(plot2)
gA <- ggplot_gtable(gb1)
gB <- ggplot_gtable(gb2)
both <- gtable:::rbind_gtable(gA, gB, "last")
png("consoletestplot.png")
grid.newpage()
grid.draw(both)
dev.off()
有没有办法来解决这个问题?非常感谢!