Search code examples
amchartsamcharts4

How to retrieve correct date inside DateAxis AxisLabel text adapter?


I am having trouble getting the right date object when trying to change the AxisLabel :

dateAxis.renderer.labels.template.adapter.add("text", function(text, target) {
  var date = target.dataItem.date, //Date Object "2020/01/01"
      labelText = text; // "Jul" for July
  return text;
});

Here, target.dataItem.date gives me a date Object with only the year initialized, with the month being set to January everytime, whereas the text parameter gives me "Jul" for July. Why is the date object not correct ?

**** EDIT ****

Here is a codepen of my problem, which in fact occurs when the chart width is too narrow so the dateAxis shows only years : https://codepen.io/XxSven/pen/rNadEPG


Solution

  • This is about "axis grid granularity". Let me explain.

    Your data spans several years. This means that axis needs to display a scale of several years. In order for it to be not too crammed up with grid lines and labels, it intuitively modifies granularity of its grid/labels.

    In your case it goes into "years" mode, meaning it displays a grid line/label for each year.

    Now it would not make sense to display a label for 2011 January, but 2013 July. The grid would be at irregular intervals, completely throwing users off the scale.

    Therefore, when in year mode, axis displays for each year's January, hence what you are seeing.

    What you CAN do is to control this granularity. It is controlled by axis renderer's minGridDistance setting. Basically it means minimum distance between grid lines.

    The less the number the more granular your grid will be.

    Let's say put it at 10 pixels:

    dateAxis.renderer.minGridDistance = 10;
    

    Now you'll getting a grid/label every 3 months. Lower the number even further and you might get to individual months, but probably face overcrowding.

    Bottom line that Date object received by label adapter is NOT a date of the actual data item in your data. It's a date of the grid line DateAxis wants to place to depict its scale progression.

    You can read more about granularity of grid here.