maged
maged

Reputation: 889

chartjs - Drawing vertical line on integer x axis value

In the below example, the chartjs annotation works with a string value ("MAR"), but not with an integer value. How do I draw a vertical line on some integer x-axis value.

var chartData = {
  labels: ["JAN", "FEB", "MAR"],
  datasets: [
    {
      data: [12, 3, 2]
    }
  ]
};

window.onload = function() {
  var ctx = document.getElementById("canvas").getContext("2d");
  new Chart(ctx, {
    type: "line",
    data: chartData,
    options: {
      annotation: {
        annotations: [
          {
            type: "line",
            mode: "vertical",
            scaleID: "x-axis-0",
            value: 2,
            borderColor: "red",
            label: {
              content: "TODAY",
              enabled: true,
              position: "top"
            }
          }
        ]
      }
    }
  });
};

See fiddle: https://codepen.io/anon/pen/QaQWba

Upvotes: 6

Views: 7244

Answers (1)

beaver
beaver

Reputation: 17647

You can achieve your goal passing data as points, configuring xAxes as linear and creating a custom tick format:

Data:

var chartData = {
  labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
  datasets: [
    {
      data: [{x: 1, y: 12}, {x: 2, y: 3}, {x: 3, y: 2}, {x: 4, y: 1}, {x: 5, y: 8}, {x: 6, y: 8}, {x: 7, y: 2}, {x: 8, y: 2}, {x: 9, y: 3}, {x: 10, y: 5}, {x: 11, y: 11}, {x: 12, y: 1}];
    }
  ]
};

xAxes config:

xAxes: [{
  type: 'linear',
  position: 'bottom',
  ticks: {
        max: 12,
        min: 1,
        stepSize: 1,
        callback: function(value, index, values) {
             return chartData.labels[index];
        }
   }
}]

Check the CodePen updated: https://codepen.io/beaver71/pen/XVZXOM

Upvotes: 5

Related Questions