0

To highlight regions in a timeseries I use layout > shapes objects, as described here: How to add colored background bars in plotly.js chart

Now each of these background shapes has a "type", and I would like the user to be able to show/hide specific types, just like with traces (e.g. show only V4 and V5, hide V3, as in the example below).

enter image description here

Is this possible?

Davor Josipovic
  • 5,296
  • 1
  • 39
  • 57

1 Answers1

1

This can in principle achieved by using traces insetad of shapes to specify the background regions. This way the background regions show up in the legend. Using some random example data try this:

library(plotly)
set.seed(42)
d <- data.frame(
  x=as.Date(c('2015-02-01', '2015-02-02', '2015-02-03', '2015-02-04', '2015-02-05',
     '2015-02-06', '2015-02-07', '2015-02-08', '2015-02-09', '2015-02-10',
     '2015-02-11', '2015-02-12', '2015-02-13', '2015-02-14', '2015-02-15',
     '2015-02-16', '2015-02-17', '2015-02-18', '2015-02-19', '2015-02-20',
     '2015-02-21', '2015-02-22', '2015-02-23', '2015-02-24', '2015-02-25',
     '2015-02-26', '2015-02-27', '2015-02-28')),
  y=runif(28, 350, 550)
)
d

range_y <- list(min = floor(min(d$y) / 100) * 100, max = ceiling(max(d$y) / 100) * 100)

shape1 <- data.frame(x = as.Date(c('2015-02-01', '2015-02-08')), y = c(range_y$max, range_y$max))
shape2 <- data.frame(x = as.Date(c('2015-02-23', '2015-02-27')), y = c(range_y$max, range_y$max))

plot_ly(x=~x, y=~y) %>% 
  add_trace(data = d, mode = "lines+markers", type = "scatter") %>% 
  add_trace(data = shape1, mode = "none", fill = "tozeroy", name = "type1") %>% 
  add_trace(data = shape2, mode = "none", fill = "tozeroy", name = "type2") %>% 
  layout(yaxis = list(range = c(range_y$min, range_y$max)))

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51
  • This is indeed a viable solution. +1. Note though that a limit on the y-axis has to be specified in this case. The reason why I initially opted to use the `layout > shape` is because then the bars can range vertically from `-Inf` up to `Inf`. – Davor Josipovic Jun 19 '20 at 13:10
  • Yep. That's a drawback of using the trace. – stefan Jun 19 '20 at 13:18