如何在 R 中为 dygraph 鼠标悬停添加标签?

How to add a label to a dygraph mouseover in R?

我一直在尝试使用 dygraphR 中绘制时间序列。似乎我们只能传入一个包含日期及其值的数据框。所有其他列将被自动忽略。在这里我复制了我的数据和结果图:

library(dygraphs)
library(tidyverse)
library(plotly)
library(data.table)


dates <- seq(as.POSIXct("2021-01-01 05:00:00"), as.POSIXct("2021-01-05 05:00:00"), by = 8*3600)


df <- data.table(date = dates,
                 percentage = round(runif(length(dates), min = 0, max = 1), digits = 2), 
                 team = sample(c("A", "B", "C", "D", "E"), size = length(dates), replace = T)
)


dygraph(df) %>%
  dyOptions(drawPoints = T, pointSize = 3) %>%
  dyAxis(name = "y", label = "percentage") %>%
  dyLegend(show = "follow")

图表如下所示:

我们可以看到每个日期对应的球队并没有在图例中显示。我希望看到鼠标悬停的团队。更清楚地说,我可以设法使用 ggplotggplotly 来做到这一点,但是,plotly 包相对较重,我仍然想为我的 [=17= 使用 dygraph ] 应用。这是使用 ggplotly 的样子:

p <- ggplot(df, aes(x = date, y = percentage)) + geom_line() + geom_point(aes(group = team))

ggplotly(p)

有什么方法可以将标签添加到 dygraph 并实现相同的目的吗?我将不胜感激

您可以创建自定义 valueFormater:

valueFormatter <- function(df) {
  paste0('function(x){return ',
         paste0((paste0('x==',as.numeric(head(df$date,-1))*1000,' ? "',head(df$date,-1),' - Team ',head(df$team,-1),'"',collapse = ":")),
                ': "',tail(df$date,1),' Team ',tail(df$team,1)),'";}')
}

日期很棘手,因为它们在 JavaScript 中以毫秒计算,因此 as.numeric(head(df$date,-1))*1000

格式化程序使用 ifelse :

生成 JavaScript 函数
cat(valueFormatter(df))

function(x){return x==1609473600000 ? "2021-01-01 05:00:00 - Team A":x==1609502400000 ? "2021-01-01 13:00:00 - Team C":x==1609531200000 ? "2021-01-01 21:00:00 - Team E":x==1.60956e+12 ? "2021-01-02 05:00:00 - Team E":x==1609588800000 ? "2021-01-02 13:00:00 - Team A":x==1609617600000 ? "2021-01-02 21:00:00 - Team C":x==1609646400000 ? "2021-01-03 05:00:00 - Team D":x==1609675200000 ? "2021-01-03 13:00:00 - Team C":x==1.609704e+12 ? "2021-01-03 21:00:00 - Team B":x==1609732800000 ? "2021-01-04 05:00:00 - Team A":x==1609761600000 ? "2021-01-04 13:00:00 - Team B":x==1609790400000 ? "2021-01-04 21:00:00 - Team C": "2021-01-05 05:00:00 Team C";}

此函数可由 dyGraphs 通过 valueFormatter 参数使用:

dygraph(df[,.(date,percentage)]) %>%  dyOptions(drawPoints = T, pointSize = 3) %>%
                                      dyAxis('x',valueFormatter = valueFormatter(df))