I have the shiny app below in which I want to download a plotly plot using downloadhandler(). But as you will see when I run the app in web browser and download the image the lower section of the histogram is missing. Why does this happen? Can this be fixed or be downloaded alternativelly? In case you wonder why I have used uiOutput() for download button and the movies dataset it is because this is how my original and more complex app works. Before you begin:
library(webshot)
install_phantomjs()
#uir.r
library(shiny)
library(plotly)
library(ggplot2movies) # movies is no longer contained within ggplot2 https://cran.r-project.org/web/packages/ggplot2movies/index.html
shinyUI(fluidPage(
titlePanel("Movie Ratings!"),
sidebarPanel(
uiOutput("down")
),
mainPanel(
plotlyOutput("trendPlot")
)
))
#server.r
library(shiny)
library(plotly)
library(ggplot2movies) # movies is no longer contained within ggplot2 https://cran.r-project.org/web/packages/ggplot2movies/index.html
shinyServer(function(input, output) {
output$down<-renderUI({
output$downloadData <- downloadHandler(
filename = function(){
paste0(paste0("pic"), ".png")
},
content = function(file) {
export(reg(), file=file)
})
downloadButton("downloadData", "Download")
})
reg<-reactive({
movies
# Create axes titles as lists
x <- list(
title = "A",
dtick = 5
)
y <- list(
title = "B"
)
# Create the plotly histogram
plot_ly(alpha = 0.9) %>%
add_histogram(x = as.factor(movies$rating)) %>%
# Add titles in plot and axes
layout(barmode = "overlay",title = "SAD",xaxis=x,yaxis=y)
})
output$trendPlot <- renderPlotly({
reg()
})
})
SPOLIED IMAGE
Related
I have a Shiny app which reads in data from a spreadsheet and produces two plots - a box plot and a histogram. I want to be able to download each plot separately (as png) using a download button when I have made various adjustments using sliders etc.
My plots work, and the download buttons work, but will only download one of the plots (apparently the one that was drawn most recently). In a reactive environment this is not very predictable and does not do what I want.
My question is, how do I specify in the download function which of the two plots to download?
An abbreviated version of my code is here:
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
<... various components ...>
}}
h3("Save the Box Plot"),
downloadButton("SaveBox", label = "Save Box Plot as PNG"),
h3("Save the Histogram"),
downloadButton("SaveHist", label = "Save Histogram as PNG")
),
mainPanel(
## Display the Boxplot
plotOutput("BoxPlot"),
## Display the Histogram
plotOutput("Hist"),
)
)
)
server <- function(input, output) {
############
## Read file and process data
graphData <- reactive ({
... draw box plot ...
})
################################
## Display the box plot
output$BoxPlot <- renderPlot({
...
})
################################
## Display the histogram
output$Hist <- renderPlot({
... draw histogram ...
})
################################
## Save to PNG with the plot title as a default file name.
## Skip saving if no file has been loaded
## Save file using the system file save utility so you can name it and put it where you want
output$SaveBox = downloadHandler(
filename = function(file){
ifelse (is.null(input$DataFile),return(), str_c(input$Title, ".png"))
},
content = function(file) {
ggsave(file, width = 290, height = 265, units = "mm", device = "png")
}
)
output$SaveHist = downloadHandler(
filename = function(file){
ifelse (is.null(input$DataFile),return(), str_c(input$HistTitle, ".png"))
},
content = function(file) {
ggsave(file, width = 290, height = 265, units = "mm", device = "png")
}
)
)
The issue is that you have to tell ggsave which plot you want to save. If not specified the last plot will be saved. To fix you code you could move the plot codes into reactives, which could then be called both in the renderPlots and passed to the plot argument of ggsave so that the right plot is saved:
I adjusted your code a bit to make it a reproducible example using mtcars as example data:
library(shiny)
library(ggplot2)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
h3("Save the Box Plot"),
downloadButton("SaveBox", label = "Save Box Plot as PNG"),
h3("Save the Histogram"),
downloadButton("SaveHist", label = "Save Histogram as PNG")
),
mainPanel(
## Display the Boxplot
plotOutput("BoxPlot"),
## Display the Histogram
plotOutput("Hist")
)
)
)
server <- function(input, output) {
## Read file and process data
graphData <- reactive({
mtcars
})
box_plot <- reactive({
ggplot(graphData(), aes(mpg)) +
geom_boxplot()
})
hist_plot <- reactive({
ggplot(graphData(), aes(mpg)) +
geom_histogram()
})
## Display the box plot
output$BoxPlot <- renderPlot({
box_plot()
})
## Display the histogram
output$Hist <- renderPlot({
hist_plot()
})
output$SaveBox <- downloadHandler(
filename = function(file) {
"box_plot.png"
#ifelse(is.null(input$DataFile), return(), str_c(input$Title, ".png"))
},
content = function(file) {
ggsave(file, plot = box_plot(), width = 290, height = 265, units = "mm", device = "png")
}
)
output$SaveHist <- downloadHandler(
filename = function(file) {
"hist_plot.png"
#ifelse(is.null(input$DataFile), return(), str_c(input$HistTitle, ".png"))
},
content = function(file) {
ggsave(file, , plot = hist_plot(), width = 290, height = 265, units = "mm", device = "png")
}
)
}
shinyApp(ui, server)
I am trying to insert a bar graph from a dataset that I have into Shiny to make a simple bar graph of the data. This is my code thus far:
library(plotly)
library(shiny)
library(readxl)
excel_data <- read_excel(path = system.file("CHAMPdata_gender/datasets.xlxs", package = "readxl"))
ui <- fluidPage(
mainPanel(
plotlyOutput("chart")
)
)
server <- function(input, output, session) {
output$chart <- renderPlotly({
# write code here to read data from csv file
# Set x and y axis and display data in bar chart using plotly
p <- plot_ly( x = CHAMPdata_gender$X,
y = CHAMPdata_gender$Total.Respond, CHAMPdata_gender$Never, CHAMPdata_gender$Less.than.one.year, CHAMPdata_gender$One.year.or.more,
name = "Childhood data",
type = "bar")
})
}
shinyApp(ui, server)
I am currently trying to learn Shiny in R, so would appreciate all the help I can get! thanks
I want the bar plot to be embedded into application.output of vector d is giving me result I want that to be embedded into shinyapp and later I want to make it interactive too.
library(ggplot2)
driver1 <- read.csv("E:/RMARKDOWN/shiny/driver.csv",header = T)
New_DataSet1<-
data.frame(driver1$ï..Year_AG,driver1$Severity_Desc,driver1$Injury.Type)
New_DataSet1
latest <- New_DataSet1[1:100,]
latest
d <- aggregate(latest$driver1.Injury.Type, by=list(chkID =
latest$driver1.Severity_Desc), FUN=sum)
ui <- dashboardPage(
dashboardHeader(title = "Row layout"),
dashboardSidebar(),
dashboardBody()
)
server <- function(input, output) {
#output$plot <- renderPlot({ barplot(d$x, xlab = d$chkID) })
renderPlot(d$x)
#barplot(d$x, xlab = d$chkID)
# barplot(d$x, names.arg = d$chkID)
}
shinyApp(ui,server)
You can read file first and render it using bar chart as below:
library(plotly)
library(shiny)
ui <- fluidPage(
mainPanel(
plotlyOutput("chart")
)
)
server <- function(input, output, session) {
output$chart <- renderPlotly({
# write code here to read data from csv file
df=read.csv("")
# Set x and y axis and display data in bar chart using plotly
p <- plot_ly( x = iris$Species,
y = iris$Sepal.Length,
name = "Iris data",
type = "bar")
})
}
shinyApp(ui, server)
Screenshot from working demo:
How to export plot_ly image as png from shiny app? I want to export png or jpg on action button 'ExportPlot' (as specified below). I know about plot_ly solution https://plot.ly/r/static-image-export/ however it require to create user on plot_ly as i read about it.
I would be grateful for any tips/solution.
library(shiny)
library(plotly)
ui <- fluidPage(
actionButton('ExportPlot', 'Export as png'),
plotlyOutput("plot"),
verbatimTextOutput("event")
)
server <- function(input, output) {
# renderPlotly() also understands ggplot2 objects!
output$plot <- renderPlotly({
plot_ly(mtcars, x = ~mpg, y = ~wt)
})
output$event <- renderPrint({
d <- event_data("plotly_hover")
if (is.null(d)) "Hover on a point!" else d
})
}
shinyApp(ui, server)
Here is the solution which provides download on click:
library(shiny)
library(plotly)
ui <- fluidPage(
downloadButton('ExportPlot', 'Export as png'),
plotlyOutput("plot")
)
server <- function(input, output) {
# generate the plot
thePlot <- reactive({
p <- plot_ly(mtcars, x = ~mpg, y = ~wt)
})
# renderPlotly()
output$plot <- renderPlotly({
thePlot()
})
# download
output$ExportPlot <- downloadHandler(
# file name
filename <- 'plot.png',
# content
content = function(file){
# create plot
export(p = thePlot(), file = 'tempPlot.png')
# hand over the file
file.copy('tempPlot.png',file)
}
)
}
shinyApp(ui, server)
Please note: With the RStudio browser/viewer the file name which is set per default is not correctly hand over, with external Browsers (e.g. Firefox) it should work.
I've recently started learning Shiny and am developing my first practice app. For some reason, my app doesn't take up the entire browser window but is cutoff about half way. The page can still scroll down to see the rest of the output but there is a high fold for some reason. Below is my code:
library(foreign)
library(dplyr)
library(shiny)
library(dplyr)
library(ggplot2)
library(shinythemes)
thesis <- read.csv("thesis.csv", stringsAsFactors = T)
ui <- fluidPage(theme = shinytheme("cerulean"),
# Application title
titlePanel("Annual Prices by City"),
# Sidebar with choice selected
sidebarLayout(
sidebarPanel(
selectInput("city","City",as.character(thesis$city)),
tableOutput("table")
),
# Show a time series line plot
mainPanel(
textOutput("cityheader"),
plotOutput("plot", width="100%")
)
)
)
server <- function(input, output, session) {
df <- reactive({
thesis %>%
select(city, year, price) %>%
filter(city == input$city)
})
output$plot <- renderPlot({
ggplot(df(), aes(x=year, y=price)) +
labs(title=input$city, x="Year", y="Annual Avg Price") +
geom_line(col="blue")
}, height=400, width = 700)
output$table <- renderTable({
df()
})
output$cityheader <- renderText({
input$city
})
}
shinyApp(ui=ui,server=server)
Here is a screenshot of the white space:
Screenshot of the Shiny App
UPDATE:
Here is what it looks like from within the viewer's pane in Rstudio:
Rstudio Screenshot
Thanks.
I had the same issue, try
shinyApp(ui = ui, server = server, options = list(height = 1080))