Adding multiple reactive geom_lines to Shiny figure

Viewed 404

I'd like to include the reactive outputs of two data sets as different geom_lines in the same ggplotly figure. The code runs as expected when only one reactive data.frame is included as a geom_line. Why not two?

ui <- fluidPage(


   sidebarLayout(

  selectInput("Var1",
     label = "Variable", #DATA CHOICE 1
     selected = 10,
     choices = c(10:100)),

   selectInput("Var1",
               label = "Variable2", #DATA CHOICE 2
               selected = 10,
               choices = c(10:100))

      # Show a plot of the generated distribution

   ),
  mainPanel(
    plotlyOutput('plot') #Draw figure
  )
)


server <- function(input, output) {

  out <- reactive({

    data.frame(x = rnorm(input$Var1), #Build data set 1
               y  = 1:input$Var1)

  })

  out2 <- reactive({
    data.frame(x = rnorm(input$Var2), #Build data set 2
               y  = 1:input$Var2)
  })

  output$plot <- renderPlotly({
    p <- ggplot() +
      geom_line(data = out(), aes(x = x, y = y)) #Add both data sets in one ggplot
      geom_line(data = out2(), aes(x = x, y = y), color = "red")

    ggplotly(p)
  })

}

# Run the application 
shinyApp(ui = ui, server = server)
1 Answers

When you put the data into long format and give each group a group identifier it seems to work. Note that you should be able to change sliderInput back to selectInput - this was one of the entries I toggled during testing, but the choice of UI widget should not matter.

This works -- code can be simplified inside the reactive from here:

library(plotly)

  ui <- fluidPage(

  sidebarLayout(
     sliderInput("Var1",
            label = "Variable", #DATA CHOICE 1
            min=10, max=100, value=10),
     sliderInput("Var2",
            label = "Variable2", #DATA CHOICE 2
            min=10, max=100, value=10),
  ),
  mainPanel(
     plotlyOutput('plot') #Draw figure
  )
)

   server <- function(input, output) {

   out <- reactive({
      x1 <- rnorm(input$Var1)
      y1 <- seq(1:input$Var1)
      x2 <- rnorm(input$Var2)
      y2 <- seq(1:input$Var2)
      xx <- c(x1,x2)
      yy <- c(y1,y2)
      gg <- c( rep(1,length(y1)), rep(2,length(y2)) )
      df <- data.frame(cbind(xx,yy,gg))
      df
   })

   output$plot <- renderPlotly({
   p <- ggplot() +
       geom_line(data=out(), aes(x = xx, y = yy, group=gg, colour=gg))
   ggplotly(p)
   })

 }

shinyApp(ui = ui, server = server)

enter image description here

Related