score:2

Accepted answer

Here is an example of what you can do using annotation plugin and custom drawing on canvas:

var data_set = [{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}];
var labels = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];

var lines = [], id = 0;
var linesOn = false;

var data = {
  labels: labels,
  datasets: [{
    label: "My First dataset",
    backgroundColor: "rgba(5,215,2,0.2)",
    borderColor: "rgba(5,215,2,1)",
    borderWidth: 2,
    hoverBackgroundColor: "rgba(5,215,2,0.4)",
    hoverBorderColor: "rgba(5,215,2,1)",
    data: data_set,
  }]
};
addLine(7);
var option = {
  legend: false,
  title: {
    display: true,
  },
  annotation: {
    drawTime: "afterDraw",
    annotations: lines
  },
  scales: {
    xAxes: [{
      id: 'x-axis',
      type: 'linear',
      position: 'bottom',
      ticks: {
        max: 12,
        min: 1,
        stepSize: 1,
        callback: function(value, index, values) {
          return data.labels[index];
        }
      }
    }],
    yAxes: [{
      id: 'y-axis',
      type: 'linear',
    }],
  },
  animation: {
    duration: 1,
    onComplete: function () {
      var ctx = this.chart.ctx;
      console.log("onComplete", this,Chart.defaults.global)
      ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);    
      ctx.textAlign = "center";
      ctx.textBaseline = "bottom";
      var line = this.chart.annotation.elements.line1,
      x = line._model.x1-15,
      y = line._model.y1+5;
      ctx.fillStyle = line.options.label.fontColor;
      ctx.fillText("Y",x,y);
		}
  }
};

var myLineChart = Chart.Line('myChart', {
  data: data,
  options: option
});

function addLine(value) {
  id++;
  var ln = {
    id: "line" + id,
    type: "line",
    mode: "horizontal",
    scaleID: "y-axis",
    value: value,
    borderWidth: 2,
    borderColor: "red",
    label: {
      enabled: false,
      fontColor: "red",
    }
  };
  lines.push(ln);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.min.js"></script>

<canvas id="myChart" width="400" height="400"></canvas>

In the example I disabled annotation label showing and added a custom label on yAxis (see animation.onComplete() handler).


Related Query

More Query from same tag