Search code examples
rggplot2shinyggvis

reactive ggplot2 graph - customize each graph


I'm creating a shiny application with a dropdown to select a graph. I pull in data from my working directory, create a few variables, and then select these variables in ggplot2 to display the graph I'd like. However, I'd like to add some individual customization to these graphs.I'm struggling to find a way to be able to display the information differently on each graph -e.g., have different x and y names for each. Here is what I currently have:

selection <- reactive({if(input$var=="Average Price by Country") {
  return(mpc)
} else if (input$var =="Average Price by Vintage") {
  return(mpv)
} else if (input$var == "Standard Deviation by Country") {
  return(sdc)
} 
})

output$plot <- renderPlot({

  function() {
    if(selection ==mpc) {
    selection() %>%
    ggplot(aes(V1, V2, fill = V3)) +
    geom_bar(stat = "identity", position="dodge")    
    }else {
    selection() %>%
    ggplot(aes(V1, V2, fill = V3)) +
    geom_bar(stat = "identity", position="dodge")    
    }
  }
})

Average price by Country, Average Price by Vintage and Standard deviation by Country are all options in a dropdown in the UI. Ideally, I'd like to be able to customize each ggvis graph differently. The way it's currently set up, it just displays different data with the same ggvis function. I tried to wrap selection in outputplot but this didn't even display the graph when I ran the app.

Is there any way to write a function to do this? Thank you.


Solution

  • I can't see the rest of your code, so I can't test it, but this is what I would do:

    output$plot <- renderPlot({
      if(input$var == "Average Price by Country") {
        selection <- mpc
        plot_type = "mpc"
      } else if (input$var =="Average Price by Vintage") {
        selection <- mpv
        plot_type = "mpv"
      } else if (input$var == "Standard Deviation by Country") {
        selection <- sdc
        plot_type = "sdc"
      } 
      if(plot_type == "mpv") { # CHANGE ME
          selection %>%
            ggplot(aes(V1, V2, fill = V3)) +
            geom_bar(stat = "identity", position="dodge")    
        }else {
          selection %>%
            ggplot(aes(V1, V2, fill = V3)) +
            geom_bar(stat = "identity", position="dodge")    
        }
    }
    

    The big assumption being that mpc, mpv and sdc are in the workspace. (ie, load("yourworkspace.RData") before shinyServer())