I am trying to download the graph I made in Shiny, I found a Stackoverflow post about this subject here . However, when I run the code from the answer, all seeems to work fine, exept that I can't open the graphs once they are "saved". I can't see them in the folder I saved them in and when I try to open them from my recent files, an error "file not found" pops up.
This is the code I'm using:
library(shiny)
library(ggplot2)
runApp(list(
#ui
ui = fluidPage(downloadButton('downloadPlot')),
#server
server = 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$downloadPlot <- downloadHandler(
filename = function() { paste(input$dataset, '.png', sep='') },
content = function(file) {
ggsave(file, plot = plotInput(), device = "png")
}
)
}
))
I tried to replicate your code with textInput and this works fine for me.
library(shiny)
library(ggplot2)
runApp(list(
#ui
ui = fluidPage(downloadButton('downloadPlot'),
textInput("filename", "Choose a dataset:")),
#server
server = function(input, output) {
datasetInput <- reactive({
switch(input$filename,
"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$downloadPlot <- downloadHandler(
filename = function() { paste(input$filename, '.png', sep='') },
content = function(file) {
ggsave(file, plot = plotInput(), device = "png")
}
)
}
))
Alternatively, you can use plotly
which supplies a download possibility without further configurations (download button is in the upper right corner of the graph):
library(shiny)
library(plotly)
runApp(list(
#ui
ui = fluidPage(selectInput("dataset", "Choose a dataset:", choices = c("rock", "pressure", "cars")),
plotlyOutput('plot')),
#server
server = function(input, output) {
datasetInput <- reactive({
switch(input$dataset,
"rock" = rock,
"pressure" = pressure,
"cars" = cars)
})
output$plot <- renderPlotly({
df <- datasetInput()
ggplot(df, aes_string(x=names(df)[1], y=names(df)[2])) +
geom_point()
ggplotly()
})
}
))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.