Learn how to use Dash Bio for next-gen sequencing & quality control. 🧬Register for the Oct 27 webinar.

Range Selector - Auto Scale Y-Axis

I’m trying to get the y-axis to scale when I click a range selector button. It’s an issue because if I look at one month’s worth of data it looks flat unless I manually change the y-axis. Here’s a repeatable example of what I’m trying to fix:

x <- data.frame(Date = seq(Sys.Date()-365, Sys.Date(), by = 1), Value = 366:1) 

p <- plot_ly(x = x$Date, y = x$Value, type = 'scatter', mode = 'lines') %>%
  layout(
    xaxis = list(title = "", type = 'date', rangeselector = list(
      buttons = list(
        list(count = 30, label = "30 days", step = "day", stepmode = "backward")
        , list(step = "all", label = 'All')
      )
    ))
  )

When you click the “30 days” button it changes the range of the x-axis, but not the y-axis leaving the graph really flat.

Is there any way to automatically reset the y-axis when a range selector button is clicked?

Thanks in advance!

Seems similar to this issue – https://github.com/ropensci/plotly/issues/912

Yep, that seems to be the same issue. Unfortunately, my Javascript skills are a bit rusty, but I think my solution is easier to get to now. I’m trying to use this plot in a Shiny app, which gives me the ability to use whatever javascript I want in the app.

shinyApp(
  ui = fluidPage(
    tags$head(tags$script("//some javascript here")),
    plotlyOutput('myChart')
    ),
  server = function(input, output){
    x <- data.frame(Date = seq(Sys.Date()-365, Sys.Date(), by = 1), Value = 366:1)
    
    p <- plot_ly(x = x$Date, y = x$Value, type = 'scatter', mode = 'lines') %>%
      layout(
        xaxis = list(type = 'date', rangeselector = list(
          buttons = list(
            list(count = 30, label = "30 days", step = "day", stepmode = "backward")
            , list(step = "all", label = 'All')
          )
        ))
      )
    output$myChart = renderPlotly(p)
  }
)

The Javascript solution mentioned in that forum is rather long and I’m not sure how I can apply it to my R Plotly. I imagine I could add some Javascript to the head of my Shiny app using the same logic and point it at the correct plot… if I knew Javascript a little better. Any ideas?