![](/img/trans.png)
[英]Dygraph with R - How to use axisLabelFormatter for label's character size?
[英]How to add a label to a dygraph mouseover in R?
我一直在嘗試使用dygraph
中的R
plot 時間序列。 看來我們只能傳入帶有日期及其值的 dataframe 。 所有其他列將被自動忽略。 在這里,我復制了我的數據和結果圖:
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")
這里的圖表是這樣的:
正如我們所見,每個日期對應的團隊並未顯示在圖例中。 我想看到鼠標懸停的團隊。 更清楚地說,我可以使用ggplot
和ggplotly
來做到這一點,但是, plotly
package 相對較重,我仍然想在我的Shiny
應用程序中使用 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
function :
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
參數使用這個 function:
dygraph(df[,.(date,percentage)]) %>% dyOptions(drawPoints = T, pointSize = 3) %>%
dyAxis('x',valueFormatter = valueFormatter(df))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.