问题
I'm having problems downloading a plot created with grid.draw() in the downloadHandler() function in Shiny. Here is a reproducible example of what I want to achieve:
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)
When I press Download as png, this shows up in the console:
Error opening file: 2
Error reading: 9
In the console, this code runs fine and the plot saves as expected:
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()
Is there a way to fix this? Many thanks!
回答1:
The content function has to have an argument, it can be anything (for instance "file") and it then goes to png() function.
#Changes:
content <- function(file){ ## file = NULL --> file
png(file) # filename --> file
Full code:
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",
# Changes:
content <- function(file){ ## file = NULL --> file
png(file) # filename --> file
grid.newpage()
grid.draw(plotting())
dev.off()
}
)
}
shinyApp(server=server,ui=ui)
来源:https://stackoverflow.com/questions/32260858/download-plot-created-with-grid-draw-as-png-in-downloadhandler-shiny