Search code examples
javascriptdateaxis-labelsamcharts4

AmCharts v4 linechart, starts dateaxis 1 month late


Using amcharts 4 i am displaying an xy chart (simple line graph). Each datapoint has the data set in chart.data, the first as and the following with 1 week intervals:

{
   "Date": new Date(2015, 12, 31), 
   "Value: 12345,
   "LineColor: "#000000"
}, {
   "Date": new Date(2016, 01, 07), 
   "Value: 234567,
   "LineColor: "#000000"
}

Despite this, the first dateAxis point displayed on the chart is (after formatting) Sun 31 Jan 2016, which is not among the dates input.

If i change the dateAxis.baseInterval to timeUnit: "week", count: 1 I get 28 jan 2016, which is amongst the input dates, but the 5th from the top.

I have been searching for something similar to this problem, but it does not seem like this is a commonly experienced problem. Am I missing out on some piece of code that forces the dateaxis to actually use the date input?

Sorry for the lack of code example, if needed i can include more, but currently it's on a secluded machine.


Solution

  • Note that your first date is not December. Months in the JavaScript Date API go from 0-11, which explains why it gets set to January instead and the second date is in Feburary.

    If you want more granularity in your axis, set the baseInterval to a day instead of a week/seven days:

    dateAxis.baseInterval = {
      "timeUnit": "day",
      "count": 1
    };
    

    If you only want to show labels from your data, set skipEmptyPeriods to true as well.

    dateAxis.skipEmptyPeriods = true;
    

    Demo below:

    var chart = am4core.create("chartdiv", am4charts.XYChart);
    
    chart.data = generateData();
    
    var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
    dateAxis.renderer.grid.template.location = 0;
    dateAxis.renderer.minGridDistance = 50;
    dateAxis.baseInterval = {
      "timeUnit": "day",
      "count": 1
    };
    dateAxis.skipEmptyPeriods = true;
    
    var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
    
    var series = chart.series.push(new am4charts.LineSeries());
    series.dataFields.valueY = "value";
    series.dataFields.dateX = "date";
    series.tooltipText = "{dateX}: [b]{valueY}[/]";
    series.strokeWidth = 2; 
    
    function generateData() {
      var data = [];
      var firstDate = new Date(2015, 11, 31);
      var i;
      for (i = 0;  i < 15;  ++i) {
        var nextDate = new Date(firstDate);
        nextDate.setDate(nextDate.getDate() + (7 * i));
        data.push({
          "date": nextDate,
          "value": Math.floor(Math.random() * 100 + 1 * i)
        });
      }
      return data;
    }
    
    chart.cursor = new am4charts.XYCursor();
    #chartdiv {
      width: 100%;
      height: 350px;
    }
    <script src="//www.amcharts.com/lib/4/core.js"></script>
    <script src="//www.amcharts.com/lib/4/charts.js"></script>
    <div id="chartdiv"></div>