【问题标题】:How to add a label to a dygraph mouseover in R?如何在 R 中为 dygraph 鼠标悬停添加标签?
【发布时间】:2021-08-06 23:19:26
【问题描述】:

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

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 包相对较重,我仍然想在我的Shiny 应用程序中使用dygraph。下面是使用 ggplotly 的样子:

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

ggplotly(p)

有什么方法可以给 dygraph 添加标签并实现同样的效果?我会很感激任何帮助

【问题讨论】:

    标签: r label dygraphs


    【解决方案1】:

    您可以创建一个自定义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

    格式化程序使用ifelseshorthand ternary operator生成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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      • 2015-03-29
      • 2011-08-04
      • 2018-09-03
      相关资源
      最近更新 更多