References in axis using chart.js in line chart - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

References in axis using chart.js in line chart

Demo Code

ResultView the demo in separate window

<html lang="en">
   <head> 
      <title>Chart.js - Add Point Annotation</title> 
   </head> 
   <body translate="no"> 
      <div style="width: 75%"> 
         <canvas id="canvas"></canvas> 
      </div> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> 
      <script>
      window.chartColors = {/* w ww . j a v  a  2s .c om*/
  red: 'rgb(255, 99, 132)',
  orange: 'rgb(255, 159, 64)',
  yellow: 'rgb(255, 205, 86)',
  green: 'rgb(75, 192, 192)',
  blue: 'rgb(54, 162, 235)',
  purple: 'rgb(153, 102, 255)',
  grey: 'rgb(231,233,237)'
};
Chart.plugins.register({
  afterDraw: function(chartInstance) {
    if (chartInstance.config.options.showDatapoints || chartInstance.config.options.showDatapoints.display) {
      var showOnly = chartInstance.config.options.showDatapoints.showOnly || [];
      var helpers = Chart.helpers;
      var ctx = chartInstance.chart.ctx;
      var fontColor = helpers.getValueOrDefault(chartInstance.config.options.showDatapoints.fontColor, chartInstance.config.options.defaultFontColor);
      ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize + 5, 'normal', Chart.defaults.global.defaultFontFamily);
      ctx.textAlign = 'center';
      ctx.textBaseline = 'bottom';
      ctx.fillStyle = fontColor;
      chartInstance.data.datasets.forEach(function (dataset) {
        for (var i = 0; i < dataset.data.length; i++) {
          if (showOnly.includes(dataset.data[i])) {
            var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
            var scaleMax = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._yScale.maxHeight;
            var yPos = (scaleMax - model.y) / scaleMax >= 0.93 ? model.y + 20 : model.y - 5;
            ctx.fillText(dataset.data[i], model.x, yPos);
          }
        }
      });
    }
  }
});
var ctx = document.getElementById("canvas").getContext("2d");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: 'APPL Price',
      borderColor: window.chartColors.blue,
      borderWidth: 2,
      fill: false,
      data: [5, 3, 4, 10, 8, 9, 2]
    }]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: 'Chart.js - Add Point Annotations'
    },
    showDatapoints: {
      display: true,
      showOnly: [3, 10, 9]
    },
    tooltips: {
      mode: 'index',
      intersect: true
    },
    scales: {
      yAxes: [{
        ticks: {
          max: 12
        }
      }]
    }
  }
});
    
      </script>  
   </body>
</html>

Related Tutorials