这是我找到的解决方案。绘图是在反应函数中使用 ggplot2 生成的。该对象用于在屏幕上呈现它,也用于以 png 和 pdf 格式下载。
我还添加了一个小部件来调整绘图的纵横比,基于示例here。调整将在所有三个版本中使用。
library(shiny)
library(ggplot2)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "AspectRatio",
label = h5("Aspect Ratio"),
choices = .1 * (5:20),
selected = 1.5
),
downloadButton("DownloadPNG", "PNG"),
downloadButton("DownloadPDF", "PDF")
),
mainPanel(
plotOutput("Plot")
)
)
)
server <- function(input, output) {
# Generate plot in a reactive function
myPlot <- reactive({
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_point()
})
output$Plot <- renderPlot({
myPlot()
},
height = 500,
width = function() {
round(500 * as.numeric(input$AspectRatio))
}
)
#Download vector graphics in PDF
output$DownloadPDF <- downloadHandler(
filename = "chart.pdf",
content = function(file) {
pdf(
file,
width = round(6 * as.numeric(input$AspectRatio)),
height = 6
)
print(myPlot())
dev.off()
}
)
# Download plot in PNG format in high resolution
output$DownloadPNG <- downloadHandler(
filename = "chart.png",
content = function(file) {
png(
file,
width = round(2500 * as.numeric(input$AspectRatio)),
height = 2500,
res = 360
)
print(myPlot())
dev.off()
}
)
}
shinyApp(ui = ui, server = server)