2

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")
    })
  }
)
Mriti Agarwal
  • 204
  • 1
  • 7

1 Answers1

3

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

Ben
  • 28,684
  • 5
  • 23
  • 45
  • Thank you so much @Ben! This works. Could you please help me further with this? I want to dynamically add new events to this gantt, so I am taking input from the user and adding it to the data frame, so how can I change the length of the vertical line? Say we add 2 more events so now, the length will be 10 but how can we make the system calculate that it should add two more to yend? – Mriti Agarwal Oct 08 '20 at 03:39
  • @MritiAgarwal Please see edited answer. I'm not entirely sure about this, but it appears you could pull out the yaxis range by using `plotly_build`. Would this solve the problem? – Ben Oct 08 '20 at 13:10