保存在一个闪亮的应用程序进行绘图 [英] Save plots made in a shiny app

查看:188
本文介绍了保存在一个闪亮的应用程序进行绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何使用downloadButton来保存闪亮的情节。包中的示例演示了downloadButton / downloadHandler以保存.csv。 $ b

对于 ui.R

  shinyUI(pageWithSidebar(
headerPanel('Downloading Data')),
sidebarPanel(
selectInput(dataset ,选择数据集,
选择= c(摇滚,压力,汽车)),
downloadButton('downloadData','下载数据'),
下载按钮('downloadPlot','Download Plot')
),
mainPanel(
plotOutput('plot')

))

对于 server.R

  library(ggplot2)
shinyServer(function(input,output){
datasetInput< - reactive({
switch(input $数据集,
摇滚=摇滚,
压力=压力,
汽车=汽车)
})

plot输入<无效的({
df < - datasetInput()
p <-ggplot(df,aes_string(x = names(df)[1],y = names(df)[2])) )+
geom_point()
})

输出$ plot < - renderPlot({
print(plotInput())
})

output $ downloadData< - downloadHandler(
filename = function(){paste(输入$ dataset,'.csv',sep ='')},
content = function文件){
write.csv(datatasetInput(),file)
}

output $ downloadPlot< - downloadHandler(
filename = function(){paste (输入$ dataset,'.png',sep ='')},
content = function(file){
ggsave(file,plotInput())
}

))

如果您回答这个问题,您可能对此很熟悉,但要实现这一点,请将上述内容保存到单独的脚本中( ui.R server.R )到文件夹中 foo )在工作目录中。要运行闪亮的应用程序,请运行 runApp(foo)使用 ggsave运行

,我收到一条错误消息,指出ggsave不能使用文件名函数(我认为)。如果我使用标准图形设备(如下所示), Download Plot 可以正常工作,但不会写入图形。



获得downloadHandler写作图的任何提示都值得赞赏。

解决方案

不知道这个问题仍然活跃,但它是第一个在搜索在闪亮的应用程序中保存情节时出现的,所以我想快速添加如何使ggsave与downloadHandler一起工作,与原始问题一致。

由juba使用直接输出替代ggsave和替代策略建议的替代策略,由alexwhan自己提出,这两种策略都很好,这仅仅适用于那些绝对想要使用ggsave的人

alexwhan报告的问题是由ggsave试图将文件扩展名与正确的图形设备相匹配导致的。但是,临时文件没有扩展名,所以匹配失败。这可以通过在 ggsave 函数调用中专门设置设备来解决,就像在原始代码示例中一样(对于png):

  output $ downloadPlot<  -  downloadHandler(
filename = function(){paste(输入$ dataset,'.png',sep ='')} ,
content = function(file){
device< - function(...,width,height)grDevices :: png(...,width = width,height = height,res = 300 ,units =in)
ggsave(file,plot = plotInput(),device = device)
}

这个调用基本上将设备函数用于 png ggsave 在内部分配(可以查看 ggsave 函数代码以查看 jpg pdf 等)。也许,理想情况下,可以用 ggsave 参数指定文件的扩展名(如果与文件名不同 - 如同临时文件的情况那样),但是此选项是当前的在 ggsave 中不可用。






最小的独立工作例如:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ ui = fluidPage(downloadButton('foo')),
server = function(input,output){
plotInput = function(){
qplot(speed,dist,data = cars)
}
输出$ foo = downloadHandler(
文件名='test.png',
content =函数(文件){
设备< - function(... ,宽度,高度){
grDevices :: png(...,width = width,height = height,
res = 300,units =in)
}
ggsave(file,plot = plotInput(),device = device)
})
}
))

sessionInfo( )
#R版本3.1.1(2014-07-10)
#平台:x86_64-pc-linux-gnu(64位)

#locale:$ LC_CONATE = zh_CN.UTF-8
#[5] LC_MONETARY = en_US .UTF-8 LC_MESSAGES = en_US.UTF-8
#[7] LC_PAPER = en_US.UTF-8 LC_NAME = C
#[9] LC_ADDRESS = C LC_TELEPHONE = C
#[11 ] LC_MEASUREMENT = en_US.UTF-8 LC_IDENTIFICATION = C

#附加的基本软件包:
#[1] stats graphics grDevices utils datasets methods base

#其他附加软件包:
#[1] ggplot2_1.0.0 shiny_0.10.1

#通过命名空间加载(并未附加):
#[1] bitops_1.0- 6 caTools_1.17 colorspace_1.2-4 digest_0.6.4
#[5] formatR_1.0 grid_3.1.1 gtable_0.1.2 htmltools_0.2.6
#[9] httpuv_1.3.0 labeling_0.2 MASS_7.3- 34 munsell_0.4.2
#[13] plyr_1.8.1 proto_0.3-10 Rcpp_0.11.2 reshape2_1.4
#[17] RJSONIO_1.3-0 scales_0.2.4 stringr_0.6.2 tools_3.1.1
#[ 21] xtable_1.7-3



更新



从ggplot2版本2.0.0开始, ggsave 函数支持 device 参数的字符输入,这意味着临时文件由downloadHandler创建,现在可以通过直接调用 ggsave 来保存,方法是指定要使用的扩展名应该是eg pdf(而不是传入设备函数)。这将上面的例子简化为以下内容:

  output $ downloadPlot<  -  downloadHandler(
filename = function(){粘贴(输入$ dataset,'.png',sep ='')},
content = function(file){
ggsave(file,plot = plotInput(),device =png)
}


I'm trying to figure out how to use downloadButton to save a plot with shiny. The example in the package demonstrates downloadButton/downloadHandler to save a .csv. I'm going to make a reproducible example based on that.

For ui.R

shinyUI(pageWithSidebar(
  headerPanel('Downloading Data'),
  sidebarPanel(
selectInput("dataset", "Choose a dataset:", 
            choices = c("rock", "pressure", "cars")),
    downloadButton('downloadData', 'Download Data'),
    downloadButton('downloadPlot', 'Download Plot')
  ),
  mainPanel(
    plotOutput('plot')
  )
))

For server.R

library(ggplot2)
shinyServer(function(input, output) {
  datasetInput <- reactive({
    switch(input$dataset,
           "rock" = rock,
           "pressure" = pressure,
           "cars" = cars)
  })

  plotInput <- reactive({
    df <- datasetInput()
    p <-ggplot(df, aes_string(x=names(df)[1], y=names(df)[2])) +
      geom_point()
  })

  output$plot <- renderPlot({
    print(plotInput())
  })

  output$downloadData <- downloadHandler(
    filename = function() { paste(input$dataset, '.csv', sep='') },
    content = function(file) {
      write.csv(datatasetInput(), file)
    }
  )
  output$downloadPlot <- downloadHandler(
    filename = function() { paste(input$dataset, '.png', sep='') },
    content = function(file) {
      ggsave(file,plotInput())
    }
  )
})

If you're answering this question, you are probably familiar with this, but to get this working, save the above into separate scripts (ui.R and server.R into a folder (foo) within the working directory. To run the shiny app, run runApp("foo").

Using ggsave, I get an error message indicating that ggsave can't use the filename function (I think). If I use the standard graphics device (like below), the Download Plot works without an error, but it doesn't write the graphic.

Any tips to get downloadHandler working for writing plots would be appreciated.

解决方案

Not sure if this question is still active but it's the first one that came up when searching for "saving plots in shiny app" so I wanted to quickly add how to get ggsave to work with downloadHandler along the lines of the original question.

The alternative strategies suggested by juba using direct output instead of ggsave and alternative strategy suggested by alexwhan himself both work great, this is just for those who absolutely want to use ggsave in the downloadHandler).

The problem reported by alexwhan is caused by ggsave trying to match the file extension to the correct graphics device. The temporary file, however, doesn't have an extension so the matching fails. This can be remedied by specifically setting the device in the ggsave function call, like so in the original code example (for a png):

output$downloadPlot <- downloadHandler(
    filename = function() { paste(input$dataset, '.png', sep='') },
    content = function(file) {
        device <- function(..., width, height) grDevices::png(..., width = width, height = height, res = 300, units = "in")
        ggsave(file, plot = plotInput(), device = device)
    }
)

This call basically takes the device function for a png that ggsave assigns internally (you can look at the ggsave function code to see the syntax for jpg, pdf, etc). Perhaps, ideally, one could specify the file extension (if different from the file name - as is the case here for the temporary file) as a ggsave parameter but this option is currently not available in ggsave.


A minimal self-contained working example:

library(shiny)
library(ggplot2)
runApp(list(
  ui = fluidPage(downloadButton('foo')),
  server = function(input, output) {
    plotInput = function() {
      qplot(speed, dist, data = cars)
    }
    output$foo = downloadHandler(
      filename = 'test.png',
      content = function(file) {
        device <- function(..., width, height) {
          grDevices::png(..., width = width, height = height,
                         res = 300, units = "in")
        }
        ggsave(file, plot = plotInput(), device = device)
      })
  }
))

sessionInfo()
# R version 3.1.1 (2014-07-10)
# Platform: x86_64-pc-linux-gnu (64-bit)
# 
# locale:
#  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
#  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
#  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
#  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
#  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
# [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
# 
# attached base packages:
# [1] stats     graphics  grDevices utils     datasets  methods   base     
# 
# other attached packages:
# [1] ggplot2_1.0.0 shiny_0.10.1 
# 
# loaded via a namespace (and not attached):
#  [1] bitops_1.0-6     caTools_1.17     colorspace_1.2-4 digest_0.6.4    
#  [5] formatR_1.0      grid_3.1.1       gtable_0.1.2     htmltools_0.2.6 
#  [9] httpuv_1.3.0     labeling_0.2     MASS_7.3-34      munsell_0.4.2   
# [13] plyr_1.8.1       proto_0.3-10     Rcpp_0.11.2      reshape2_1.4    
# [17] RJSONIO_1.3-0    scales_0.2.4     stringr_0.6.2    tools_3.1.1     
# [21] xtable_1.7-3    

Update

As of ggplot2 version 2.0.0, the ggsave function supports character input for the device parameter, that means the temporary file created by the downloadHandler can now be saved with a direct call to ggsave by specifying that the extension to be used should be e.g. "pdf" (rather than passing in a device function). This simplifies the above example to the following

output$downloadPlot <- downloadHandler(
    filename = function() { paste(input$dataset, '.png', sep='') },
    content = function(file) {
        ggsave(file, plot = plotInput(), device = "png")
    }
)

这篇关于保存在一个闪亮的应用程序进行绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆