Joe
Joe

Reputation: 369

missing data charted within Shiny app via Plotly

Good Afternoon,

I am trying to plot a simple time series from the economics dataset from ggplot2. The app loads, then displays the chart with the correct axis, but none of the plot data is included. Any help would be very much appreciated. Best, Joe

library(shiny)
library(plotly)
library(tidyverse)

df <- economics

datalst = colnames(df)

ui <- pageWithSidebar(
  headerPanel("test"),
  sidebarPanel(
    selectInput(inputId = "x",
                label = "Choose the x axis",
                datalst),
    selectInput(inputId = "y",
                label = "Choose the y axis",
                datalst, datalst[[2]])


  ),
  mainPanel(

    plotlyOutput("plot")

  )
)

server <- function(input, output) {

    dataset  <- reactive({
      df[, c(input$x, input$y)]
    })


    output$plot = renderPlotly({

      plot_ly(dataset(), x = ~input$x, y = ~input$y,type = 'scatter', mode = 'lines')

    })

}  

shinyApp(ui = ui, server = server)

Upvotes: 1

Views: 112

Answers (1)

lbusett
lbusett

Reputation: 5932

The trick here is to avoide Non Standard Evaluation, because input$x and input$y evaluate to strings, while using plotly as in your example requires bare column names after the ~. YOu can fix this using, for example:

server <- function(input, output) {

    dataset  <- reactive({
      df[, c(input$x, input$y)]
    })
    output$plot = renderPlotly({
      plot_ly(x = dataset()[[input$x]], y = dataset()[[input$y]],type = 'scatter', mode = 'lines')
    })

}  

A further improvement could be to "split" the reactive in two, so that the inputs of the plot are invalidated and recomputed only when the corresponding input is changed:

server <- function(input, output) {

    dataset_x  <- reactive({
      df[, input$x]
    })

    dataset_y  <- reactive({
      df[, input$y]
    })
    output$plot = renderPlotly({
      plot_ly(x = dataset_x()[[1]], y = dataset_y()[[1]], type = 'scatter', mode = 'lines')
    })

}  

Upvotes: 1

Related Questions