0
votes

I'm trying to create a chart that has a dropdown where the user can select what to display on the chart (like a 'filter' in a Power BI chart, but I want to stay in R). So I'm going with Shiny and Plotly (any other suggestions welcome!).

Most tutorials point towards hard coding the input selections, but I have thousands of selections so I want this list to be generated dynamically from a field in my data source. Here's a sample of where I've got to so far, I want the dropdown to let the user select between Home 1 and Home 2:

library(shiny)
library(plotly)

df <- data.frame(Name = c("Home 1", "Home 1", "Home 2", "Home 2"), Rating = c("Good", "Excellent", "Good", "Good"),
                     Date = c("2016-07-14", "2016-08-14", "2016-07-14", "2016-08-14"))


# Get a basic shiny app working with dropdowns
ui <- fluidPage(
  plotlyOutput("plot"),
  selectInput(df$Name, "Select Name", df$Name),
  verbatimTextOutput("event")
)

server <- function(input, output) { 
  output$plot <- renderPlotly({
    plot_ly(df, x = df$Date, y = df$Rating, type = 'scatter', mode = 'line')
  })

  output$event <- renderPrint({
    d <- event_data("plotly_hover")
    if (is.null(d)) "Hover on a point!" else d
  })
}

shinyApp(ui, server)

I don't know where to put the selected input from selectInput() into the plot_ly() function, so this code obviously throws a bunch of warnings and doesn't work.

Warning in if (!is.na(attribValue)) { :
  the condition has length > 1 and only the first element will be used
Warning in charToRaw(enc2utf8(text)) :
  argument should be a character vector of length 1
all but the first element will be ignored

I feel like I'm close but I'm exhausted and basically need someone much better at this than me to point me in the right direction.

Or is there a better way using packages other than shiny & plotly?

Thanks

1

1 Answers

1
votes

Here is how I'd approach this:

library(shiny)
library(plotly)

df <- data.frame(Name = c("Home 1", "Home 1", "Home 2", "Home 2"), Rating = c("Good", "Excellent", "Good", "Good"),
                 Date = c("2016-07-14", "2016-08-14", "2016-07-14", "2016-08-14"))

# Get a basic shiny app working with dropdowns
ui <- fluidPage(
  plotlyOutput("plot"),
  selectInput("SelectName", "Select Name", df$Name, selected = unique(df$Name), multiple = TRUE),
  verbatimTextOutput("event")
)

server <- function(input, output) { 

  filteredDf <- reactive({
    req(input$SelectName)
    df[df$Name %in% input$SelectName, ]
  })

  output$plot <- renderPlotly({
    plot_ly(filteredDf(), x = ~Date, y = ~Rating, type = 'scatter', mode = 'line', color = ~Name)
  })

  output$event <- renderPrint({
    d <- event_data("plotly_hover")
    if (is.null(d)) "Hover on a point!" else d
  })
}

shinyApp(ui, server)

You'll need to create a reactive (filtered) dataset from your df (which I called filteredDf)