How to add a vertical line in a vistime plotly?

656 Views Asked by At

I want to add a vertical line representing the current date in my vistime plot. I have tried multiple ways and still haven't been able to figure it out. Here is a small reproducible code that you can build on.

library(shiny)
library(plotly)
library(vistime)

pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
                   Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
                   start = c("1789-03-29", "1797-02-03", "1801-02-03"),
                   end = c("1797-02-03", "1801-02-03", "1809-02-03"),
                   color = c('#cbb69d', '#603913', '#c69c6e'),
                   fontcolor = c("black", "white", "black"))

shinyApp(
  ui = plotlyOutput("myVistime"),
  server = function(input, output) {
    output$myVistime <- renderPlotly({
      vistime(pres, col.event = "Position", col.group = "Name")
    })
  }
)
1

There are 1 best solutions below

2
On BEST ANSWER

You can use add_segments to add a vertical line to your plotly timeline made with vistime. The xaxis will be the year, in this example. The yaxis presidents are placed at y = 1, 3, 5, 7, so the segment should extend from 0 to 8 in this example (y = 0 and yend = 8).

Edit: To obtain the yaxis range from the plotly object automatically, you could try using plotly_build and pull out the layout attributes that way.

curr_year = 1801

p <- vistime(pres, col.event = "Position", col.group = "Name") %>%
  layout(showlegend = FALSE)
      
pb <- plotly_build(p)

add_segments(p, 
             x = curr_year, 
             xend = curr_year, 
             y = pb$x$layout$yaxis$range[1], 
             yend = pb$x$layout$yaxis$range[2], 
             color = I("light green"))

Plot

plot with vertical segment