Multiple reactive conductors in ggplot call

Hi everyone,

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("Var2",
                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)


Hi @Noj! Welcome!

I'm afraid it looks like there are a couple of errors preventing your example from running:

  • the library() statements are missing
  • both inputs are called Var1, but the server() code references input$Var2

(Maybe take a look at the tips in our Shiny Debugging & Reprex Guide?)

However, I suspect the source of the problem you're asking about is just a typo — you seem to be missing the + between your two geom_line() layers. Try this, instead:

    p <- ggplot() +
      geom_line(data = out(), aes(x = x, y = y)) +
      geom_line(data = out2(), aes(x = x, y = y), color = "red")

2 Likes

Hi @jcblum, thanks for your response. I fixed the errors and the code appears to be working now.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.