score:4

Accepted answer

the plugin core api offers a range of hooks that may be used for performing custom code. you can use the beforedraw hook to draw lines of different style between different datapoints using text directly on the canvas using canvasrenderingcontext2d.

in case the last data point shall be of different color as well, you can define dataset.bordercolor as an array. it should contain an entry for each value, all being identical except the last one. this can be done with array.map() as follows.

bordercolor: data_array.map((v, i) => i + 1 == data_array.length ? 'rgb(0, 0, 255)' : 'rgba(255, 99, 132)'),

please have a look at the runnable code snippet below.

const data_array = [307.65, 309.54, 307.71, 314.96, 313.14, 319.23, 316.85, 318.89, 316.73, 318.11, 319.55];

var mychart = new chart('mychart', {
  type: 'line',  
  plugins: [{
    beforedraw: chart => {
      var ctx = chart.chart.ctx;
      ctx.save();
      var xaxis = chart.scales['x-axis-0'];
      var yaxis = chart.scales['y-axis-0'];
      data_array.foreach((value, index) => {
        if (index > 0) {
          var valuefrom = data_array[index - 1];
          var xfrom = xaxis.getpixelfortick(index - 1);
          var yfrom = yaxis.getpixelforvalue(valuefrom);
          var xto = xaxis.getpixelfortick(index);
          var yto = yaxis.getpixelforvalue(value);      
          ctx.linewidth = 5;
          if (index + 1 == data_array.length) {            
            ctx.setlinedash([5, 5]);
            ctx.strokestyle = 'rgb(0, 0, 255)';
          } else {
            ctx.strokestyle = 'rgb(255, 99, 132)';            
          }
          ctx.beginpath();
          ctx.moveto(xfrom, yfrom);
          ctx.lineto(xto, yto);
          ctx.stroke();
        }
      });
      ctx.restore();
    }
  }],
  data: {
    labels: ['2020/05/13', '2020/05/14', '2020/05/15', '2020/05/18', '2020/05/19', '2020/05/20', '2020/05/21', '2020/05/22', '2020/05/26', '2020/05/27', '2020/05/29'],
    datasets: [{
      label: 'count',
      data: data_array,
      tension: 0,
      showline: false,
      bordercolor: data_array.map((v, i) => i + 1 == data_array.length ? 'rgb(0, 0, 255)' : 'rgba(255, 99, 132)'),
      borderwidth: 5
    }]
  },
  options: {
    animation: {
        duration: 0
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.9.3/chart.min.js"></script>
<canvas id="mychart" height="100"></canvas>


Related Query

More Query from same tag