r - 从 Shiny App 保存用户生成的 ggplot
问题描述
我正在尝试使用 ggplot 创建一个闪亮的 Web 应用程序,并包含一个下载生成的绘图的功能。这里分别是我的 UI 和服务器文件。
服务器
shinyServer(function(input, output, session) {
vals <- reactiveValues()
output$Plot <- renderPlot({
gg <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
vals$gg <- gg
print(gg)
}, height = function() {
session$clientData$output_BehPlot_width
} )
# downloadHandler contains 2 arguments as functions, namely filename, content
output$down <- downloadHandler(
filename = function() {
paste("behavior", input$var3, sep=".")
},
# content is a function with argument file. content writes the plot to the device
content = function(filename) {
if(input$var3 == "png"){
png(filename) # open the png device
#ggsave(vals$gg)
print(vals$gg) # for GGPLOT
dev.off() # turn the device off
}
else {
#ggsave(vals$gg)
pdf(filename) # open the pdf device
print(vals$gg) # for GGPLOT
dev.off() # turn the device off
}
}
)
})
用户界面
shinyUI(fluidPage(
# Application title
titlePanel("TEST SHINY"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
radioButtons(inputId = "var3", label = "Select the file type", choices = list("png", "pdf")),
downloadButton("downloadPlot", "Download")
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("Plot", height="auto", width = "auto")
)
)
))
这是基于对几个先前的 Stack Overflow 线程和 Github 要点的咨询而构建的。(例如这个:R Shiny 节省反应性 ggplots)
当我在 R 控制台和浏览器的测试会话中运行下载功能时,结果是一个不打印绘图的 HTML 文件。有什么我想念的吗?
谢谢!
解决方案
您可以使用plotly
包来执行此操作。作为奖励,您的情节将是互动的。要保存绘图,请查看 plotly 绘制的右上角图标菜单。
library(plotly)
# use plotlyOutput instead of plotOutput in UI
# use renderPlotly instead of renderPlot in server
# wrap your ggplot in ggplotly
output$Plot <- renderPlotly(
ggplotly(ggplot(mtcars, aes(mpg, wt)) + geom_point())
)
注意:在您的代码中,您不必将绘图放在反应变量中,因为它不会触发观察者或渲染器。一个简单的变量就可以完成这项工作。
推荐阅读
- spring - JPA findBy...IgnoreCase 和 PostgreSQL 索引
- java - EditText 视图未在新行上扩展
- sql - 如何根据参数对 x 个表列进行求和?
- javascript - 如何使用 gulp-babel 编译 nodejs Gulp-Task 并忽略“导入”?
- c++ - 如何使用 protobuf 描述符读取枚举
- unity3d - Unity 中的门户着色器
- checkbox - 三态复选框作为 MFC 对话框中 GroupBox 元素的标签
- c# - 在将树结构序列化为 JSON 期间强制转换异常
- r - 根据其他data.frame过滤和加入data.frame
- excel - 在 Excel 中计算时间/天之间的时间