I'm new to Shiny and have been developing a web app that displays a plotly chart; I'm still developing the app on my local machine. When I run the app for the first time after opening RGui, the web app runs but does not render the chart, even after I have clicked the "Draw" button. I have to refresh the webpage once or twice and then the chart will render. Once the chart has rendered, the problem is gone for the duration of that R session. Refreshing the page or restarting the shiny program will continue to render the chart, until RGui is closed. The problem reliably recurs the next time I open RGui and run the app.
All the existing questions and answers I have searched on shiny and failed rendering have not answered my question.
After several frustrated attempts at trying to find what was wrong in my program, I boiled it down to this code that looks (to me) like it should be functional, but still presents the issue:
library(shiny)
library(plotly)
ui = fluidPage(
plotlyOutput("Plot"),
actionButton("drawPlotButton", "Draw")
)
server = function(input, output)
{
output$Plot = renderPlotly({
input$drawPlotButton
return(plot_ly(mtcars, x = ~hp, y = ~mpg, type = "scatter", mode = "markers"))
})
}
shinyApp(ui = ui, server = server)
I can't tell if I am missing something simple or what. All help is appreciated.
Generally runs fine for me as in the plot renders at initialization.
However, if your objective is to plot the graph only when the Draw button is clicked then:
You need to add a eventReactive method
See r Shiny action button and data table output
library(shiny)
library(plotly)
ui = fluidPage(
plotlyOutput("Plot"),
actionButton("drawPlotButton", "Draw")
)
server = function(input, output)
{
plot_d <- eventReactive(input$drawPlotButton, {
plot_ly(mtcars, x = ~hp, y = ~mpg, type = "scatter", mode = "markers")
})
output$Plot = renderPlotly({
plot_d()
})
}
shinyApp(ui = ui, server = server)
Related
I need to create shiny app which will create a plot basing on dropdown menu choise. The whole computation part is pretty complicated and so is the plot – I created a function which is returning ggplot and I just wanted to show it in the app.
My idea looks as follows:
library(shiny)
source('Analysis/function_external.R')
list_names = c('a', 'b', 'c')
ui <- fluidPage(
selectInput("data", "Select data to plot", choices = list_names)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
observe({function_external(input$data)})
}
# Run the application
shinyApp(ui = ui, server = server)
It is making function run every time I change the input, but it does not show anything. I would really appreciate if you can point me into good direction.
output$my_complicated_plot <- renderPlot({ function_external(input$data) })
Solved the issue.
I found the rshiny script is super hard to debug.
Especially, the rshiny bottom is the RunAPP. If I get the error. I did not see any hints from the Console.
Could I ask how you guys debug the rshiny?
Thanks
Most of all: always keep in mind that you need to test and debug your code. Do not just write code to satisfy requirements. Consider testing and debugging to be a requirement itself. That mind set is a good starting point to follow these rules:
R-Studio provides quite some functionality useful for debugging: step-by-step execution of your code, a trace of function calls, inspection of variables, and the opportunity to run your own code on the console while the app is on hold.
If breakpoints do not work (sometimes they just won't), add browser() to your code which creates a "forced" breakpoint.
Sometimes print() helps getting additional information output to the console.
Clearly separate the business logic from the UI. Use unit tests (testthat). If errors occur, write some sample code to test the business logic outside the shiny app.
Here is an example of how I debug in Shiny:
library(shiny)
ui <- fluidPage(
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
mainPanel(
plotOutput("distPlot")
)
)
)
server <- function(input, output) {
x <- reactive({
faithful[, 2]
})
bins <- reactive({
seq(min(x()), max(x()), length.out = input$bins + 1)
})
observe(print(bins())) # THIS LINE WILL PRINT OUTPUT TO CONSOLE
output$distPlot <- renderPlot({
hist(x(), breaks = bins(), col = 'darkgray', border = 'white')
})
}
shinyApp(ui = ui, server = server)
The observe(print(reactive_object_name())) will print a reactive object to the console, which allows you to inspect what happens to a reactive object when you change inputs in the app.
I've created a Shiny app, which contains some Plotly objects. All works fine when previewing in RStudio. Though, when I deploy the app to Shiny server (on-premise) and open the app, the plots are not shown. When looking at the developer console in the browser (Chrome or Safari) I see the following error Can't find variable: Plotly which points to line 141 of plotly.js, which is var plot = Plotly.plot(graphDiv, x) in the following code:
//if no plot exists yet, create one with a particular configuration
if (!instance.plotly) {
var plot = Plotly.plot(graphDiv, x);
instance.plotly = true;
instance.autosize = x.layout.autosize || true;
instance.width = x.layout.width;
instance.height = x.layout.height;
I tested this in Chrome and Safari, and it happens in both browsers, though when I refresh the page in Chrome the plots sometimes work.
So to test this further, I took this code from the Plotly website, and deployed it to our Shiny server environment to see if the same behaviour occurs, which is the case. As such I don't think I made a coding mistake.
I'm using the following package versions:
plotly 4.7.1
shiny 1.0.5
htmlwidgets 1.0
Shiny Server v1.5.3.838
Does anyone know how to solve this? Am I missing some packages or does something need to be configured in Shiny server to make this work?
Thanks!
I think what you may need is renderPlotly instead of renderPlot in your server. If you do this, the plot will show up on the viewer, but not in the shiny popup (blank graph) and won't work when deployed. An example of this where renderPlot has been replaced by renderPlotly is:
ui <- dashboardPage(skin = "blue",
dashboardHeader(title= "Fig. 11: State Forecasting and Nowcasting", titleWidth = 450),
dashboardSidebar(disable=TRUE),
dashboardBody(
fillPage(padding = 0,
box(title="", id="normal", solidHeader = TRUE, status = "primary", width=7,
plotlyOutput("plot1", height = 250)),
box(title="State to Examine", background = "black", width=5,
selectInput("variable", "State:", choices= sort(unique(afteradd2$State)), selected="Ohio")),
box(title="Forecast Length", background = "black", width=5,
selectInput("variable.two", "Forecast:", choices= c("Nowcast", "Three Month Forecast",
"Six Month Forecast"), selected="Nowcast"))
)))
server <- function(input, output) {
output$plot1<- renderPlotly({
par(mfrow=c(1,1))
par(mar = c(4, 5, 4, 4))
fstate(input$variable, input$variable.two)})}
shinyApp(ui=ui, server=server)
Without seeing your code it's difficult to know for sure though. If this isn't your issue could you share your code so I can try to help?
I'm looking at implementing 3D interactive plots in my shiny App, and so far I've been using plotly. However, plotly has one major disadvantage, it's extremely slow when rendering.
I've done checks, and the whole creation of updated outplot$plot <- renderPlotly ({.....}) and plotlyOutput("plot") takes less than 0.5 seconds, despite the large data set involved. This is a know issue for years but still seems to be current.
Hence, I'm looking to use a package called car, also because it has many options, some which I particularly want that are not available in other packages. Info on the car package is here: http://www.sthda.com/english/wiki/amazing-interactive-3d-scatter-plots-r-software-and-data-visualization
The problem is that it renders in a separate popup window rather than inside the shiny app, and I want to have it inside it, or even better, add a button that allow the user to have it as a popup, but only when asked. However, i can't figure out how to jam the bugger into the actual shiny page.
Here is my minimal example with a single text element and the graph code that (in my case) keeps appearing in a separate window rather than in the app.
install.packages(c("rgl", "car", "shiny"))
library("rgl")
library("car")
library(shiny)
cars$time <- cars$dist/cars$speed
ui <- fluidPage(
hr("how do we get the plot inside this app window rather than in a popup?"),
plotOutput("plot", width = 800, height = 600)
)
server <- (function(input, output) {
output$plot <- renderPlot({
scatter3d(x=cars$speed, y=cars$dist, z=cars$time, surface=FALSE, ellipsoid = TRUE)
})
})
shinyApp(ui = ui, server = server)
There is also this package, scatterplot3d but that's not interactive
http://www.sthda.com/english/wiki/scatterplot3d-3d-graphics-r-software-and-data-visualization
And there are some RGL packages but they have the same issue (seperate window) and don't offer the options I am lookign for.
You need to use an rglwidget which takes the last rgl plot and puts in in an htmlwidget. It used to be in a separate package, but it has recently been integrated into `rgl.
Here is the code to do this:
library(rgl)
library(car)
library(shiny)
cars$time <- cars$dist/cars$speed
ui <- fluidPage(
hr("how do we get the plot inside this app window rather than in a popup?"),
rglwidgetOutput("plot", width = 800, height = 600)
)
server <- (function(input, output) {
output$plot <- renderRglwidget({
rgl.open(useNULL=T)
scatter3d(x=cars$speed, y=cars$dist, z=cars$time, surface=FALSE, ellipsoid = TRUE)
rglwidget()
})
})
shinyApp(ui = ui, server = server)
Yielding this:
I am new to Shiny R and was successful in creating my first app (YAY!)! I then tried to deploy it (or publish it) and got the following error message on the web page it opened (it was working correctly within R studio and seemed to deploy ok). I checked only the app.R box when I went to publish it.
Error: Cannot open the connection.
I have had a look at other answers on here and elsewhere but I either have used the solutions and they haven't worked or haven't understood the answers (I am pretty new to R and Shiny R). I am at my wits end and really want to get this up and running as I love what Shiny is capable of.
Can anyone help??
The code I used is;
require(shiny)
meanweights <- read.csv("meanweights.csv")
ui <- fluidPage(
selectInput(inputId = "statesel",
label="Choose a state",
choices = sort(unique(meanweights$state)),
selected = "VIC",
multiple = FALSE),
plotOutput("lineplot")
)
server <- function(input, output) {
output$lineplot <- renderPlot({
read.csv("meanweights.csv") %>%
filter(state == input$statesel) %>%
ggplot(aes(day, mean_weight, color=property_type))+
geom_line()+theme_bw(base_size = 14)
})
}
shinyApp(ui = ui, server = server)
Thanks for you time.