我正在实现R闪亮效果,该功能具有以png格式下载多个图的功能。目前,我正在使用pdf格式,该格式可以在一个文件中包含多个图。但是,我更喜欢将每个单独的图另存为* .png并将它们作为zip文件一起下载到预先指定的目录中。我检查了许多在线资源,但无法弄清楚。以下是用于下载pdf格式图的R代码。感谢您的帮助。
# download plot
output$downloadPlot <- downloadHandler(
# specify the file name
filename=function(){
paste0("individualPlots_", input$username, "_", Sys.Date(), ".pdf")
},
content=function(file){
pdf(file, width=8, height=8)
xrange <- c(as.numeric(input$threshold.start), as.numeric(input$threshold.end))
for(i in 1:nrow(summary_output())){
yrange <- c(0, ymax()[i])
plot(yfit()[[i]] ~ datsub.x()[[i]],
col = "red", pch = 2,
xlim = xrange, ylim = yrange,
xlab = "time (s)", ylab = "response (nm)", cex.lab = 1.5,
main = substr(file.name()[i], 1, nchar(as.character(file.name()[i])) - 8), cex.main = 1.5)
points(datsub.y()[[i]] ~ datsub.x()[[i]], pch = 20)
legend("bottomright", c("fitted", "true"), col = c("red", "black"),
xpd = TRUE, horiz = TRUE, inset = c(-0.05, -0.15), pch = c(2, 20), bty = 'n', cex = 1.5)
legend("top", c(paste0("kd = ", b.est()[i], " (1/s)"),
paste0("RMSE = ", y_rmse()[i])),
xpd = TRUE, horiz = TRUE, inset = c(-0.05, -0.065), bty = 'n', cex = 1.5)
}
dev.off()
})
答案 0 :(得分:1)
以下是可重现的示例:
ui.R
shinyUI( fluidPage(
titlePanel( "Application Template"), br(),
sidebarLayout(
sidebarPanel(
sliderInput( "sample.size", "Number of Samples:", min = 50, max = 500, value = 50),
downloadButton( 'plot.download', 'Download Plots')
),
# Display a histogram of the generated distribution
mainPanel(
fluidRow(
column(6, plotOutput( "norm.plot")),
column(6, plotOutput( "unif.plot"))
)
)
)
))
server.R
shinyServer(function(input, output){
# Define a function that creates a histogram of random normal data
norm.plot <- function(){
# Generate data based on the slider input from the UI file
samp <- rnorm(input$sample.size)
# Plot a histogram of the random normal sample
ggplot( data.frame( samp = samp), aes( x = samp)) +
geom_histogram( bins = 30) +
labs( x = 'Random Normal Draws', y = 'Count')
}
# Return the normal histogram to the app
output$norm.plot <- renderPlot({
return( norm.plot())
})
# Define a function that creates a histogram of random uniform data
unif.plot <- function(){
# Generate data based on the slider input from the UI file
samp <- runif(input$sample.size)
# Plot a histogram of the random uniform sample
ggplot( data.frame(samp = samp), aes(x = samp)) +
geom_histogram( bins = 30) +
labs( x = 'Random Uniform Draws', y = 'Count')
}
# Return the uniform histogram to the app
output$unif.plot <- renderPlot({
return( unif.plot())
})
# Download the plots
output$plot.download = downloadHandler(
filename = 'plots.zip',
content = function( file){
# Set temporary working directory
owd <- setwd( tempdir())
on.exit( setwd( owd))
# Save the histograms (a loop can be used here for a bunch of plots)
ggsave( 'norm_hist.png', plot = norm.plot(), device = "png")
ggsave( 'unif_hist.png', plot = unif.plot(), device = "png")
# Zip them up
zip( file, c( 'norm_hist.png', 'unif_hist.png'))
}
)
})