Dan
Dan

Reputation: 372

How to use R Plotly button functionality to show/hide data?

I have some code that loops through and plots 3 red blocks and 3 blue blocks. The goal is to use the button functionality to turn on/off the blocks. I.e. when TestA is selected the red blocks show and when TestB is selected the blue blocks show. The code initially shows the red blocks but when selecting either buttons the blue blocks show and changing the button selection doesn't resort back to showing the red blocks, I have been able to get this button functionality to work with single blocks but it appears that using a for loop to create the blocks causes problems? Any help figuring this out would be greatly appreciated.

#Start vertices of rectangles at (0,0)
x1 = 0
x2 = 0
y1 = 0
y2 = 0

width=4

listA= append(list(T,T,T,F,F,F)
listB= append(list(F,F,F,T,T,T)

updatemenus <- list(
  list(
    active = -1,
    type= 'buttons',
    buttons = list(
      list(
        label = "TestA",
        method = "update",
        args = list(list(visible = listA),
                    list(title = "TestA"))),
      list(
        label = "TestB",
        method = "update",
        args = list(list(visible = listB),
                    list(title = "TestB"))))))

#Begin plot with a blank baseplot
p <- plot_ly(width = 725, height = 725,visible=T)%>%
  layout(xaxis=list(range=c(0,width),showticklabels = F),yaxis=list(range=c(0,1625000),
                                                                    linewidth=2,autotick = TRUE,ticks = "outside",ticklen = 5,tickwidth = 2,tickcolor = toRGB("black"),
                                                                    title = "Volume [AF]"))


#Plot Red block
x1 = 0.05
x2 = width
y1 = 0
y2 = 500000


for(i in 1:3){
  y2 = y2+250000
  x2 = x2+1
  x1 =x1+1
p <- add_trace(p,type='scatter',mode='none',x = c(x1,x2,x2,x1,x1),
                 y = c(y1,y1,y2,y2,y1),visible=T,
                 fill = 'toself',fillcolor = 'rgb(233,87,62)',
                 opacity=1,line=list(color='black'),
                 hoveron = 'fills',
                 showlegend = F)
}


#Plot Blue block
x1 = 0.05
x2 = width
y1 = 0
y2 = 500000


for(i in 1:3){
  y2 = y2+250000
  x2 = x2+1
  x1 =x1+1
  p <- add_trace(p,type='scatter',mode='none',x = c(x1,x2,x2,x1,x1),
                 y = c(y1,y1,y2,y2,y1),visible=F,
                 fill = 'toself',fillcolor = 'blue',
                 opacity=1,line=list(color='black'),
                 hoveron = 'fills',
                 showlegend = F)
}

p = p %>% layout(updatemenus=updatemenus)
p

Upvotes: 1

Views: 987

Answers (1)

Dan
Dan

Reputation: 372

The problem was with the T/F list creation. I was using the following code to generate my list:

list=list(c(rep(T,3),rep(F,3)))

Which resulted in a list of length 1. Using the code:

list = c(rep(list(T),3),rep(list(F),3))

Results in a list of length 6 which is needed for this example.

Upvotes: 1

Related Questions