0

I would like to plot info from two dataframes, using plotly, to use in a Shiny app.
One is called events and has few records: I want a vertical line for each of them, with hover info. The other one is called measures, can have many records which I would like to show as lines+markers, also with hover info.

I'm almost there, except that I would like the vertical lines to automatically adjust when I zoom in and out. An example is shown in the answer to this question: Horizontal/Vertical Line in plotly

I wasn't able to include multiple shapes (couldn't find how to do it), so I drew the vertical segments first, using the yref = "paper" trick, but it's not working.

I did manage to do it with annotations, such as shown here: How to add annotations horizontal or vertical reference line in plotly? , but it's not what I want.

Here is my code. Can you tell me how I should modify it?

suppressWarnings(suppressPackageStartupMessages(library(tidyverse)))
suppressWarnings(suppressPackageStartupMessages(library(plotly)))

# Events that should appear as "zoomable" vertical lines
events <- tibble(
  description = c("First", "Second", "Third"),
  date = as.Date(c("2020-02-12", "2020-06-24", "2021-03-14") )
)

set.seed(1)
# series info should render as standard lines+markers traces
series <- tibble(
  name = rep(c("Abcd", "Efgh", "Ilkl"), 6),
  date = as.Date("2020-02-12") +  
    rep(30 * seq(1, 18, by = 3), each = 3), 
  value = round(rnorm(18, 3, 1), 1) ) #, 
  # txt = paste0(name, ": ", value, " - ", format(date, "%m/%d/%y")))

# First plot the events in the background.
# Use yref = "paper" so the segments always appear when zooming.
fig <- events %>%  
  mutate(txt = paste(description, format(date, "%m/%d") ) ) %>% 
  plot_ly() %>% 
  add_segments(x = ~ date, y = 0, 
               xend = ~ date, yend = 1, 
               text = ~ txt,
               hoverinfo = "text", 
               showlegend = FALSE,
               line = list(width = .5, yref = "paper") )  # <<<<<

# Add the series lines.
fig %>% 
  add_trace(x = ~ date, y = ~ value,
            color = ~ name, 
            type = "scatter", mode = "lines+markers", 
            line = list(width = 0.6, 
                        color = ~ name), 
            marker = list(size = 3),
            text = ~txt,
            hoverinfo = 'text', 
            data = series %>% 
              mutate(txt = paste0(name, ': ', value, 
                                  ' - ', format(date, "%m/%d/%y") ) ) )

Created on 2021-07-21 by the reprex package (v2.0.0)

ap53
  • 773
  • 1
  • 7
  • 19

0 Answers0