chartjs - 在整数x轴值上绘制垂直线

时间:2018-01-09 05:02:08

标签: chart.js

在下面的示例中,chartjs注释使用字符串值("MAR"),但不使用整数值。如何在某个整数x轴值上绘制垂直线。

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"
            }
          }
        ]
      }
    }
  });
};

请参阅小提琴:https://codepen.io/anon/pen/QaQWba

1 个答案:

答案 0 :(得分:4)

您可以将目标数据传递为points,将xAxes配置为linearcreating a custom tick format

数据:

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];
        }
   }
}]

检查CodePen已更新:https://codepen.io/beaver71/pen/XVZXOM