I'm trying to download a non-ggplot file in Shiny. I can see the plot in the app, but when I click the plotDownload button in UI, it download an EMPTY png file. Someone can have idea what I'm doing wrong??
server.R
library(shiny)
shinyServer(
function(input, output) {
plotInput <- reactive({
plot(rnorm(sample(100:1000,1)))
})
output$pngPlot <- renderPlot({ plotInput() })
output$downloadPlot <- downloadHandler(
filename = "myPlot.png",
content = function(file){
png(file, width=800, res=100)
print(plotInput())
dev.off()
})
}
)
ui.R
require(shiny)
pageWithSidebar(
headerPanel("Output to png"),
sidebarPanel(
downloadButton('downloadPlot')
),
mainPanel({ mainPanel(plotOutput("pngPlot")) })
)
Thnks.
You need to replot within the downloadHandler():
library(shiny)
shinyServer(
function(input, output) {
plotInput <- reactive({
plot(rnorm(sample(100:1000,1)))
})
output$pngPlot <- renderPlot({ plotInput() })
output$downloadPlot <- downloadHandler(
filename = "myPlot.png",
content = function(file){
png(file, width=800, res=100)
plot(rnorm(sample(100:1000,1)))
dev.off()
})
}
)
Related
I am developing shiny app and I would like to use shinyBS. But the shinyBS is not compatible with new shiny v1.0.5, entire screen gray, including modal.
I would like to plot on bsModal window.
Is there a alternative way for shinyBS?
Any idea ?
Many thanks.
Here is the code:
library(shiny)
library(shinyBS)
shinyApp(
ui =
fluidPage(
sidebarLayout(
sidebarPanel(numericInput("n", "n", 50),actionButton("go", "Go")),
mainPanel(
bsModal("modalExample", "Your plot", "go", size = "large",plotOutput("plot"),downloadButton('downloadPlot', 'Download'))
)
)
),
server =
function(input, output, session) {
randomVals <- eventReactive(input$go, {
runif(input$n)
})
plotInput <- function(){hist(randomVals())}
output$plot <- renderPlot({
hist(randomVals())
})
output$downloadPlot <- downloadHandler(
filename = "Shinyplot.png",
content = function(file) {
png(file)
plotInput()
dev.off()
})
}
)
As, I am new to shiny apps need some assistance, uploading excel file and generating table output in shiny app works fine, but can't able to download the plot to a pdf format
Here is my code
library(shiny)
library(openxlsx)
library(lattice)
runApp(
list(
ui = fluidPage(
titlePanel("plots"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose xlsx file',
accept = c(".xlsx")),
tags$hr(),
downloadButton('down',"download plot")
),
mainPanel(
tableOutput('contents'),
plotOutput('plot'))
)
),
server = function(input, output){
output$contents <- renderTable({
inFile <- input$file1
if(is.null(inFile))
return(NULL)
else
read.xlsx(inFile$datapath)
})
plotInput <- reactive({
df <- input$file1
xyplot(df[,2]~df[,1],df(),xlim=c(0,10),ylim=c(0,100),type = "b")
})
output$plot <- renderPlot({
print(plotInput())
})
output$down <- downloadHandler(
filename = function(){paste("plot",".pdf",sep=".") },
content = function(file) {
pdf(file)
xyplot(df[,2]~df[,1],df(),xlim=c(0,10),ylim=c(0,100),type = "b")
dev.off()
}
)
}
)
)
The problem was that in some parts of your code you were accessing a dynamic data frame via df() but you had never defined it.
In this kind of problem, it is best to create a reactive data frame, say, df which contains the uploaded data and is passed to other reactive parts of the code via df().
Full example:
library(shiny)
library(openxlsx)
library(lattice)
runApp(
list(
ui = fluidPage(
titlePanel("plots"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose xlsx file',
accept = c(".xlsx")),
tags$hr(),
downloadButton('down',"download plot")
),
mainPanel(
tableOutput('contents'),
plotOutput('plot'))
)
),
server = function(input, output){
df <- reactive({
inFile <- input$file1
req(inFile) # require that inFile is available (is not NULL)
# (a user has uploaded data)
# read.xlsx(inFile$datapath)
head(iris, 10)
})
output$contents <- renderTable({
# access uploaded data via df()
df()
})
plotInput <- reactive({
df <- df()
xyplot(df[,2]~df[,1], df ,xlim=c(0,10),ylim=c(0,100),type = "b")
})
output$plot <- renderPlot({
plotInput()
})
output$down <- downloadHandler(
filename = function(){paste("plot",".pdf",sep=".") },
content = function(file) {
pdf(file)
#xyplot(df[,2]~df[,1],df(),xlim=c(0,10),ylim=c(0,100),type = "b")
# you have to print the plot so that you can open pdf file
print(plotInput())
dev.off()
}
)
}
)
)
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")
}
)
}
))
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()
})
}
))
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")
}
)
}
))
This is pretty much the same question as presented here:
dynamically add plots to web page using shiny
But instead of producing a variable number of plots (which I've successfully done), I am trying to upload a selection of images into the application and display them on the user interface. Using the same approach as described in the question above, I've produced my application with the code below. But only the first image is rendering in the UI.
What obvious thing have I missed today?
R 3.2.2 (Windows 7)
shiny 0.12.2
server.R
library(shiny)
shinyServer(function(input, output) {
output$files <- renderTable(input$files)
files <- reactive({
files <- input$files
files$datapath <- gsub("\\\\", "/", files$datapath)
files
})
output$images <- renderUI({
image_output_list <-
lapply(seq_along(nrow(files())),
function(i)
{
imagename = paste0("image", i)
imageOutput(imagename)
})
do.call(tagList, image_output_list)
})
observe({
for (i in seq_along(nrow(files())))
{
local({
my_i <- i
imagename = paste0("image", my_i)
output[[imagename]] <-
renderImage({
list(src = files()$datapath[my_i],
alt = "Image failed to render")
}, deleteFile = FALSE)
})
}
})
})
ui.R
library(shiny)
shinyUI(fluidPage(
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput(inputId = 'files',
label = 'Select an Image',
multiple = TRUE,
accept=c('image/png', 'image/jpeg'))
),
mainPanel(
tableOutput('files'),
uiOutput('images')
)
)
))
Your so close! Try this:
library(shiny)
server <- shinyServer(function(input, output) {
output$files <- renderTable(input$files)
files <- reactive({
files <- input$files
files$datapath <- gsub("\\\\", "/", files$datapath)
files
})
output$images <- renderUI({
if(is.null(input$files)) return(NULL)
image_output_list <-
lapply(1:nrow(files()),
function(i)
{
imagename = paste0("image", i)
imageOutput(imagename)
})
do.call(tagList, image_output_list)
})
observe({
if(is.null(input$files)) return(NULL)
for (i in 1:nrow(files()))
{
print(i)
local({
my_i <- i
imagename = paste0("image", my_i)
print(imagename)
output[[imagename]] <-
renderImage({
list(src = files()$datapath[my_i],
alt = "Image failed to render")
}, deleteFile = FALSE)
})
}
})
})
ui <- shinyUI(fluidPage(
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput(inputId = 'files',
label = 'Select an Image',
multiple = TRUE,
accept=c('image/png', 'image/jpeg'))
),
mainPanel(
tableOutput('files'),
uiOutput('images')
)
)
))
shinyApp(ui=ui,server=server)
I changed seq_along to just 1:nrow(files()) but seq_len(nrow(files())) or seq_along(t(files())) would work to.
Is there a method to output (UI end) Shiny plots to PDF for the app user to download? I've tried various methods similar to those involving ggplot, but it seems downloadHandler can't operate in this way. For example the following just produces broken PDF's that don't open.
library(shiny)
runApp(list(
ui = fluidPage(downloadButton('foo')),
server = function(input, output) {
plotInput = reactive({
plot(1:10)
})
output$foo = downloadHandler(
filename = 'test.pdf',
content = function(file) {
plotInput()
dev.copy2pdf(file = file, width=12, height=8, out.type="pdf")
})
}
))
Very grateful for assistance.
Solved. The plot should be saved locally with pdf(), not the screen device (as with dev.copy2pdf). Here's a working example: shiny::runGist('d8d4a14542c0b9d32786'). For a nice basic model try:
server.R
library(shiny)
shinyServer(
function(input, output) {
plotInput <- reactive({
if(input$returnpdf){
pdf("plot.pdf", width=as.numeric(input$w), height=as.numeric(input$h))
plot(rnorm(sample(100:1000,1)))
dev.off()
}
plot(rnorm(sample(100:1000,1)))
})
output$myplot <- renderPlot({ plotInput() })
output$pdflink <- downloadHandler(
filename <- "myplot.pdf",
content <- function(file) {
file.copy("plot.pdf", file)
}
)
}
)
ui.R
require(shiny)
pageWithSidebar(
headerPanel("Output to PDF"),
sidebarPanel(
checkboxInput('returnpdf', 'output pdf?', FALSE),
conditionalPanel(
condition = "input.returnpdf == true",
strong("PDF size (inches):"),
sliderInput(inputId="w", label = "width:", min=3, max=20, value=8, width=100, ticks=F),
sliderInput(inputId="h", label = "height:", min=3, max=20, value=6, width=100, ticks=F),
br(),
downloadLink('pdflink')
)
),
mainPanel({ mainPanel(plotOutput("myplot")) })
)
(Hello), just use pdf :
library(shiny)
runApp(list(
ui = fluidPage(downloadButton('foo')),
server = function(input, output) {
plotInput = reactive({
plot(1:10)
})
output$foo = downloadHandler(
filename = 'test.pdf',
content = function(file) {
pdf(file = file, width=12, height=8)
plotInput()
dev.off()
})
}
))
EDIT : I don't know... It's weird. A workaround is to use dev.copy2pdf like you did in the first place but in the reactive function instead downloadHandler :
## server.R
library(shiny)
shinyServer(
function(input, output) {
plotInput <- reactive({plot(rnorm(1000))
dev.copy2pdf(file = "plot.pdf")
})
output$myplot <- renderPlot({ plotInput() })
output$foo <- downloadHandler(
filename <- "plot.pdf",
content <- function(file) {
file.copy("plot.pdf", file)
})
}
)