I have a xts object with 3 columns and quarterly data. I would like to format my date labels with "1QYY" and successively. Now is showing "mm yyyy".
I did not understand how to use axisLabelFormatter
from dyAxis
function.
My code:
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"))
My 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")))
CodePudding user response:
Try this solution.
Using of dyAxis
function:
dyAxis("x", axisLabelFormatter=JS(//YourFunction//)
In your case (1QYY) it looks thus:
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];
}'
Also you need a library(htmlwidgets)
Adding to your code:
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))
Checking the correctness:
Before:
After: