如何在 vistime plotly 中添加垂直线?

How to add a vertical line in a vistime plotly?

我想在我的 vistime 图中添加一条代表当前日期的垂直线。我已经尝试了多种方法,但仍然无法弄清楚。 这是您可以构建的小型可重现代码。

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")
    })
  }
)

您可以使用 add_segments 向使用 vistime 制作的 plotly 时间轴添加一条垂直线。在这个例子中,xaxis 将是年份。 yaxis 总统位于 y = 1、3、5、7,因此在本例中该段应从 0 扩展到 8(y = 0yend = 8)。

编辑:要自动从plotly 对象获取yaxis 范围,您可以尝试使用plotly_build 并以这种方式提取布局属性。

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"))

情节