Recommand · October 28, 2021 0

Plotly R Updatemenu buttons is not working properly, graph disappearing

I am trying to add buttons in plotly R by using updatemenus option to change xaxis range.
I am using category array. I have 10 variable in x-axis as given below. When I use "7A" instead of "1234500" as variable at x-axis, updatemenus is working properly and it is changing graph with selected range. If I use "1234500" instead of "7A", after changing range at menu, graph is disappearing.
I could not find the reason.

I hope someone can help what is really wrong

Here is as an example code:

x<-c("1A","2A","3A","4A","5A","6A","1234500","1234501","1234502","1234503")
random_y <- sample(1:10, 10, replace=T)
random_z <- sample(1:10, 10, replace=T)
random_w <- sample(1:10, 10, replace=T)
data <- data.frame(x, random_y, random_z, random_w)

y<-ceiling(length(data$x)/3)
buttons<-vector(mode = "list", length = y)

for(i in 1:y){
  lower<-(i-1)*3
  upper<-i*3-1
    
 a<- list(
      label = as.character(i*3),
      method = "update",
      args = list(list(visible = c(T,T,T)), 
                  list(xaxis = list(range = c(lower, upper))))
      )
 buttons[[i]]<-a
}

updatemenus <- list(
  list(
    active = -1,
    type = 'dropdown',
    direction = "down",
    buttons = buttons
  )
)

fig <- plot_ly(data, x = ~x, y = ~random_y, type = 'bar') %>%
  add_trace(y = ~random_z)%>%
  add_trace(y = ~random_w)%>%
  layout(barmode = 'stack', xaxis = list(categoryorder = "array", categoryarray = ~x, range = c(0,10)),updatemenus = updatemenus
  )

fig