[Chartjs]-How to draw one line with different colors in chartjs2?

1👍

First convert your line chart into a scatter chart. Then draw the lines directly on the canvas using the Plugin Core API. The API offers a range of hooks that may be used for performing custom code.

In below code snippet, I use the beforeDraw hook to draw connection lines of different colors between data points.

const values = [11,9,7,8,7,11,13,12,7,12];
const colors = ['red','red','orange','orange','green','green','orange','red','green'];
const data = values.map((value, index) => ( { x: index + 1, y: value, color: index == 0 ? undefined: colors[index - 1]} ));

const colorsPer100 = ['green', 'orange', 'blue', 'red']; 

new Chart(document.getElementById("myChart"), {
  type: "scatter",
  plugins: [{
    beforeDraw: chart => {      
      var ctx = chart.chart.ctx; 
      var xAxis = chart.scales['x-axis-1'];
      var yAxis = chart.scales['y-axis-1'];      
      chart.config.data.datasets[0].data.forEach((value, index) => {
        if (index > 0) {        
           var valueFrom = data[index - 1];
           var xFrom = xAxis.getPixelForValue(valueFrom.x);     
           var yFrom = yAxis.getPixelForValue(valueFrom.y);
           var xTo = xAxis.getPixelForValue(value.x);         
           var yTo = yAxis.getPixelForValue(value.y); 
           ctx.save();           
           ctx.strokeStyle = value.color;          
           ctx.lineWidth = 2;
           ctx.beginPath();
           ctx.moveTo(xFrom, yFrom);             
           ctx.lineTo(xTo, yTo);
           ctx.stroke();
           ctx.restore();
        }
      });      
    }
  }],
  data: {
    datasets: [{
      label: "My Dataset",
      data: data,
      borderColor: "black"
    }]
  },
  options: {
    animation: {
      duration: 0
    },
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        ticks: {
          min: 0,
          max: 12,
          stepSize: 1
        }
      }],
      yAxes: [{
        ticks: {
          min: 0,
          max: 14,
          stepSize: 2
        }
      }]
    }
  }  
});
canvas {
  max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="10" height="6"></canvas>

0👍

Did it like this in React for 2 lines:

<Line
    data={{
      labels: [100, 200, 300, 150, 250, 400],
      datasets: [
        {
          label: 'My red line',
          fill: false,
          borderColor: 'red',
          data: [null, null, 2, 0, 3],
        },
        {
          label: 'My green line',
          fill: false,
          borderColor: 'green',
          data: [2, 4, 2, null, null, null],
        },
      ],
    }}
  />

Leave a comment