我正在使用 Shiny 的,我想创建一个下载按钮,将当前绘图存储为图像。这有效:
output$downloadPlot <- downloadHandler(
filename <- function() {
paste(input$group,'-top6_plot', Sys.Date(),'.png',sep='') },
content <- function(file) {
png(file, width = 980, height = 400, units = "px", pointsize = 12,
bg = "white", res = NA)
plot(sin, -pi, 2*pi)
dev.off()},
contentType = 'image/png'
)
但是我使用 dygraphs 来绘制动态图,这会创建一个空的白色图像:
output$downloadPlot <- downloadHandler(
filename <- function() {
paste(input$group,'-top6_plot', Sys.Date(),'.png',sep='') },
content <- function(file) {
png(file, width = 980, height = 400, units = "px", pointsize = 12,
bg = "white", res = NA)
ReshapedVariables<-variablesForPlot()
if(input$timeframe == 1){
Title ="Timeframe: 1 Month"
} else if(input$timeframe==2){
Title ="Timeframe: 3 Months"
} else if(input$timeframe==3){
Title ="Timeframe: 6 Months"
} else if(input$timeframe==4){
Title ="Timeframe: Year to date"
} else if(input$timeframe==5){
Title ="Timeframe: 3 Years"
} else if(input$timeframe==6){
Title ="Timeframe: All"
} else {
Title ="Timeframe: Year to date"
}
dygraph(ReshapedVariables, main=Title) %>%
#dyLegend(width = 200, labelsSeparateLines = TRUE, labelsDiv="VariablePlotLegend", show="always") %>%
dyLegend(labelsSeparateLines = FALSE, labelsDiv="VariablePlotLegend", show="always") %>%
dyOptions(strokeWidth=2, axisLineColor=GRAPH_BLUE, axisLabelColor=GRAPH_BLUE, gridLineWidth=0.1)
dev.off()},
contentType = 'image/png'
)
但是 dygraphs 的绘图代码一般有效......因为在 web Shiny 的应用程序中它正确显示了绘图。
最佳答案
这个问题已经很老了,但也许这个答案可能对您或其他人仍然有用。这个问题与这个问题直接相关:How to save Leaflet in R map as png or jpg file? .我遇到了与您相同的问题,这是我为我的案例解决的方法:
您需要安装包“htmlwidgets”和“webshot”。然后,
library(htmlwidgets)
library(webshot)
您还需要安装 PhantomJS。然后,
使用通用函数调用将您的绘图保存为服务器端的单独对象。您需要在单独的 react 环境中创建变量 ReshapeVariables,因此现在将其视为函数:
dyplot <- function(){
dygraph(ReshapedVariables(), main=Title) %>%
labelsDiv="VariablePlotLegend", show="always") %>%
dyLegend(labelsSeparateLines = FALSE, labelsDiv="VariablePlotLegend",show="always") %>%
dyOptions(strokeWidth=2, axisLineColor=GRAPH_BLUE, axisLabelColor=GRAPH_BLUE, gridLineWidth=0.1)}
然后下载:
output$downloadData <- downloadHandler(
filename = function () {paste(input$group,'-top6_plot', Sys.Date(),'.png',sep='') },
content = function(file) {
saveWidget(dyplot(), "temp.html", selfcontained = FALSE)
webshot("temp.html", file = file)
}
)
关于r - Shiny:将动态图导出为图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30886607/