如何更改 dygraphs 中的日期轴标签

How to change date axis labels in dygraphs

我有一个包含 3 列和季度数据的 xts 对象。我想用“1QYY”连续格式化我的日期标签。现在显示“mm yyyy”。

我不明白如何使用 dyAxis 函数中的 axisLabelFormatter

我的代码:

dados_graf_1 %>%
  dygraph() %>%
  dySeries("PIB_sa", label = "PIB", color = "#c7940b", strokeWidth = 3) %>%
  dySeries("Agro_sa", label = "Agropecuária", color = "#a9a9a9", strokeWidth = 3) %>%
  dySeries("Ind_sa", label = "Indústria", color = "#206785", strokeWidth = 3) %>%
  dySeries("Serv_sa", label = "Serviços", color = "#010101", strokeWidth = 3, strokePattern = "dashed") %>%
  dyOptions(gridLineColor = "white", gridLineWidth = 0.2) %>%
  dyLegend(show = "always", hideOnMouseOut = TRUE, width = 622) %>%
  dyRangeSelector(height = 30, fillColor = "#abacae", dateWindow = c("2018-06-01", "2021-12-01"))

我的dput:

structure(c(59.4686002115258, 60.0003634242107, 62.3501901028889, 
61.7102611737569, 62.3167251492956, 62.7386272902486, 63.5178979190809, 
64.010330551864, 62.7735159185782, 63.7922085619849, 40.941808998477, 
41.469578632432, 43.7163221802143, 53.8999836721848, 43.7866060869199, 
43.0961440203287, 44.5155510158354, 48.2617616388888, 43.0388053925826, 
48.3894575959625, 78.0053327716668, 75.2249841097006, 81.916723278062, 
76.9363727724092, 80.9312975004623, 80.6444045847008, 82.2266773995473, 
81.9387558324773, 80.0399787575468, 81.2163539287905, 57.3829121992107, 
58.0993981656538, 58.9478082292876, 57.7405388428977, 59.1413925759281, 
59.3957517630808, 59.7297910855835, 60.4324312997044, 59.9485782636543, 
60.4706850605738), class = c("xts", "zoo"), index = structure(c(825638400, 
833587200, 841536000, 849398400, 857174400, 865123200, 873072000, 
880934400, 888710400, 896659200), tzone = "UTC", tclass = "Date"), .Dim = c(10L, 
4L), .Dimnames = list(NULL, c("PIB_sa", "Agro_sa", "Ind_sa", 
"Serv_sa")))

试试这个解决方案。

使用dyAxis函数:

dyAxis("x", axisLabelFormatter=JS(//YourFunction//)

在您的情况下 (1QYY) 看起来是这样的:

getQuarter <- 'function(d) {
      d = d || new Date();
      var n = [1,2,3,4];
      var qr = n[Math.floor(d.getMonth() / 3)] + "Q";
      var twoDigitsYear = parseInt(d.getFullYear().toString().substr(2,2), 10);
      return [qr+twoDigitsYear];
}'

你还需要一个library(htmlwidgets)

添加到您的代码中:

dados_graf_1 %>%
    dygraph() %>%
    dySeries("PIB_sa", label = "PIB", color = "#c7940b", strokeWidth = 3) %>%
    dySeries("Agro_sa", label = "Agropecuária", color = "#a9a9a9", strokeWidth = 3) %>%
    dySeries("Ind_sa", label = "Indústria", color = "#206785", strokeWidth = 3) %>%
    dySeries("Serv_sa", label = "Serviços", color = "#010101", strokeWidth = 3, strokePattern = "dashed") %>%
    dyOptions(gridLineColor = "white", gridLineWidth = 0.2) %>%
    dyLegend(show = "always", hideOnMouseOut = TRUE, width = 622) %>%
    dyRangeSelector(height = 30, fillColor = "#abacae", dateWindow = c("2018-06-01", "2021-12-01")) %>%
    dyAxis("x", axisLabelFormatter=JS(getQuarter))

校验正确性:

之前:

之后: