在 R 中的 vistime/plotly 时间轴中指定线条颜色

Specify line color in vistime/plotly timeline in R

我使用 R 中的 vistime 库创建了一个非常简单的时间轴:

library(vistime)
library(plotly)
data <- read.csv(text="event,group,start,end,color,line.color
                       RedBorder,Project,2016-12-22,2016-12-22,#e8a735,#FF0000
                       BlueBorder,Meetings,2012-03-15,2012-03-15,#e8a735,#0000ff
                       BlueBorder,Meetings,2017-01-12,2017-01-12,#e8a735,#0000ff
                       BlueBorder,Meetings,2019-09-12,2019-09-12,#e8a735,#0000ff
                       BlueBorder,Meetings,2018-08-15,2017-08-15,#e8a735,#0000ff
                       RedBorder,Meetings,2017-01-15,2017-01-15,#e8a735,#FF0000")

#Ordering the data, oldest to newest -- this sorts correctly
data <- data[order(data$start),]

p <- vistime(data)
pb <- plotly_build(p)

#The plot's dates are not ordered
pb$x$data[[2]]$x
#Attempting to order the plot's data.  These are the date elements. No luck ordering.
pb[order(pb$x$data[[2]]$x)] 
for (i in 1:length(pb$x$data)) {
  if (pb$x$data[[i]]$mode == "markers") pb$x$data[[i]]$marker$line$color<- data$line.color
}

pb

我正在尝试使线条颜色与 line.color 列中的内容相匹配,但如您所见,它没有为点分配正确的线条颜色。例如,RedBorder 应该有红色轮廓,BlueBorder 事件应该有蓝色轮廓。

这很棘手!似乎您对“构建的”Plotly 对象内相对于您的输入数据的数据(基于时间)的内部排序感到厌烦。

基本上,data$line.color 没有正确的排序顺序,因此颜色没有映射到正确的标记。

只需根据日期预先订购您的数据,例如order(data$start) 修复了问题。将 data 第 4 行移动到位置 3。编辑:看起来排序顺序可能更复杂,因此在制作 pb[= 之后使用 match 设置 data 的顺序19=]

使用更复杂的数据进行最终编辑: 我最初发布的编辑没有你的完整更新。您需要知道 pb$x$data 的哪个索引包含您的标记 X 位置。在您的第一个示例中它是索引 2,在您的新示例中它是索引 4。

library(vistime)
library(plotly)
data <- read.csv(text="event,group,start,end,color,line.color
                       RedBorder,Project,2016-12-22,2016-12-22,#e8a735,#FF0000
                       BlueBorder,Meetings,2012-03-15,2012-03-15,#e8a735,#0000ff
                       BlueBorder,Meetings,2017-01-12,2017-01-12,#e8a735,#0000ff
                       BlueBorder,Meetings,2019-09-12,2019-09-12,#e8a735,#0000ff
                       BlueBorder,Meetings,2018-08-15,2017-08-15,#e8a735,#0000ff
                       RedBorder,Meetings,2017-01-15,2017-01-15,#e8a735,#FF0000")


data <- as.data.frame(data)  
data$color <- rgb(1,1,1,0)

p <- vistime(data)
pb <- plotly_build(p)


for (i in 1:length(pb$x$data)) {
  if (pb$x$data[[i]]$mode == "markers") {
    data <- data[match(strftime(pb$x$data[[i]]$x, "%Y-%m-%d"), data$start),]
    pb$x$data[[i]]$marker$line$color<- data$line.color
  }
}
#> [1] 4