rcheckboxggplot2shinygeom-hline

Shiny, R: Check box, geom_hline, ggplot


in my shiny app, I would like to add a geom_hline in my ggplot only when the user selects to do so with a checkbox, also I would like the user to set the yintercept with a numericInput. I believe that there is an easy solution but as I am not a coder I would like to ask which would be the easiest way to do it. My code goes like this:

in UI:

numericInput('hline', label ='Limits', 0)

and in server:

 plotInput <- reactive({



    ggplot(data = dataforplot(), aes(x = ID_Polymer, y = value), position = position_dodge(width = 1))  +
      geom_bar(aes_string( fill=razeni()), position = position_dodge(width = 1), stat="identity", color="white")+
      theme_minimal() +
      theme(legend.text=element_text(size=21))+
      theme(text = element_text(size=21))+
      theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
      ggtitle(input$title_text_box_id) + 

      geom_hline(aes(yintercept = input$hline, linetype = "Minimal limit"), color='red', size=0.4)+

      labs(x = "", y = input$ylabel_text_box_id) + 
      geom_text(aes(x = ID_Polymer, y = value,Group=Polymer,label=value), 
                position = position_dodge(width = 1),vjust=2, size=5,colour = "white", fontface = "bold") +
      scale_fill_tableau("Tableau 10")+
     scale_x_discrete(labels=c(xpopisky()))#puts a reactive in x labels

  })

which works, only I don't know the best way to tell the shiny "show the geom_hline only when I tell you by checking the checkbox", an if else cycle should be involved I believe. Thanks a lot for any suggestions!


Solution

  • You can assign ggplot objects to a variable. The following pseudo code demonstrates this:

    p = ggplot(data = ......) +
          geom_bar(....) +
          theme(....)
    
    if(input$hline){
        p = p + geom_hline(....)
    }
    

    Note that your question would be improved if you provided a minimal working example. Right now the code in your question includes irrelevant details (e.g. ggplot theme and labels) and can not be run as is.