Search code examples
rggplot2shinyreactiveaction-button

ActionButton doesn't work properly after having click it and introduce user's input later in Shiny


I have created one app that it allows you to draw a plot. In order to show it, you need to click an actionButton. The idea is that every change you make in the plot will be changed after you have clicked the button.

However, I have added a numericInput to change the y-axis if the user chooses the option, but now the plot updates automatically and it doesn't depend on the actionButton. How can I avoid that?

Here is a reproducible example:

library(shiny)
library(ggplot2)
library(dplyr)

dt <- data.frame(x=runif(1000), y=runif(1000))

ui <- fluidPage(
  checkboxInput("change_Axis", "Change y_axis"),
  conditionalPanel(
    condition="input.change_Axis",
    numericInput("change_y_axis", label=NULL, value=1, min=1)
  ),
  actionButton("draw","plot"),
  
  plotOutput("rys")
)


server <- function(input,output){
  
  pp <- reactive({
    plot <- ggplot(dt, aes(x,y)) +
      geom_point()
    
    if(input$change_Axis){
      plot <- plot + scale_y_continuous(limits = function(x){
        c(min(x), input$change_y_axis)
      })
    }
    return(plot)
  }) %>% bindEvent(input$draw)

  
  output$rys <- renderPlot({
    pp()
  })
}

shinyApp(ui=ui, server=server)

In the app, when you click the button for the first time you get the plot. When you select for the first time to change the axis, it doesn't change automatically. You have to click the actionButton. However, if you want to change the axis again (for the second time), the plot changes automatically. And so on if you change it again.

I want to avoid changing the plot automatically after the user changes the y-axis. I want to control it through the actionButton.

Could anyone help me, please?

Thanks in advance


Solution

  • I have found the solution to my problem.

    I had to add isolate --> isolate(input$change_y_axis).

    Now the plot doesn't update.

    library(shiny)
    library(ggplot2)
    library(dplyr)
    
    dt <- data.frame(x=runif(1000), y=runif(1000))
    
    ui <- fluidPage(
      checkboxInput("change_Axis", "Change y_axis"),
      conditionalPanel(
        condition="input.change_Axis",
        numericInput("change_y_axis", label=NULL, value=1, min=1)
      ),
      actionButton("draw","plot"),
      
      plotOutput("rys")
    )
    
    
    server <- function(input,output){
      
      pp <- reactive({
        plot <- ggplot(dt, aes(x,y)) +
          geom_point()
        
        if(input$change_Axis){
          plot <- plot + scale_y_continuous(limits = function(x){
            c(min(x), isolate(input$change_y_axis))
          })
        }
        return(plot)
      }) %>% bindEvent(input$draw)
      
      
      output$rys <- renderPlot({
        pp()
      })
    }
    
    shinyApp(ui=ui, server=server)