Custom Axis Labeling in Date-Time Axis | CanvasJS

Adding custom axis labels in x-axis with control over start, end position & interval

by canvasjs

HTML

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/><!-- Just so that JSFiddle's Result label doesn't overlap the Chart -->
<div id="chartContainer" style="height: 360px; width: 100%;"></div>

JavaScript

var chart = new CanvasJS.Chart("chartContainer", {
  title: {
    text: "Custom Axis Labeling"
  },
  data: [{
    type: "spline",
    dataPoints: [
      { x: new Date(2017, 06, 01), y: 21 },
      { x: new Date(2017, 06, 02), y: 27 },
      { x: new Date(2017, 06, 03), y: 23 },
      { x: new Date(2017, 06, 04), y: 25 },
      { x: new Date(2017, 06, 05), y: 23 },
      { x: new Date(2017, 06, 06), y: 29 },
      { x: new Date(2017, 06, 07), y: 27 },
      { x: new Date(2017, 06, 08), y: 25 },
      { x: new Date(2017, 06, 09), y: 25 },
      { x: new Date(2017, 06, 10), y: 23 },
      { x: new Date(2017, 06, 11), y: 26 },
      { x: new Date(2017, 06, 12), y: 23 },
      { x: new Date(2017, 06, 13), y: 19 },
      { x: new Date(2017, 06, 14), y: 27 },
      { x: new Date(2017, 06, 15), y: 27 },
      { x: new Date(2017, 06, 16), y: 24 },
      { x: new Date(2017, 06, 17), y: 23 },
      { x: new Date(2017, 06, 18), y: 26 },
      { x: new Date(2017, 06, 19), y: 30 },
      { x: new Date(2017, 06, 20), y: 21 },
      { x: new Date(2017, 06, 21), y: 30 },
      { x: new Date(2017, 06, 22), y: 23 },
      { x: new Date(2017, 06, 23), y: 24 },
      { x: new Date(2017, 06, 24), y: 22 },
      { x: new Date(2017, 06, 25), y: 22 },
      { x: new Date(2017, 06, 26), y: 22 },
      { x: new Date(2017, 06, 27), y: 26 },
      { x: new Date(2017, 06, 28), y: 23 },
      { x: new Date(2017, 06, 29), y: 27 },
      { x: new Date(2017, 06, 30), y: 31 },
      { x: new Date(2017, 06, 31), y: 27 }
    ]
  }]
});

chart.render();
addCustomLabels(chart, chart.axisX[0], new Date(2017, 06, 01), new Date(2017, 06, 31), 5, "day");

function addCustomLabels(chart, axis, start, end, interval, intervalType) {
  axis.set("labelFormatter", function(e) {
    return "";
  });
  axis.set("tickThickness", 0);

  var intervalMultiplier = 1;

  if (axis.valueType === "dateTime") {
    if (intervalType === "year") {
      intervalMultiplier = 365 * 24 * 60 * 60 * 1000;
    } else if...