How to change line segment color based on label value in chart.js?

Viewed 555

There is an example of how to change line segment color based on point value, with a function like this

borderColor: function(context) {
   if (context.p0.parsed.y == 5){
      return 'transparent';
   }
},

I want to set the color based on the value of the label. This doesn't work:

context.p0.parsed.x == 'February'
1 Answers

With the new verion of chart.js that released today (3.6.0) you can access the chart object and you get the dataIndex so you can check it in the labels array like so:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      segment: {
        borderColor: (ctx) => (ctx.chart.data.labels[ctx.p0DataIndex] === "Green" ? "Pink" : "Orange")
      }
    }]
  },
  options: {}
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdn.jsdelivr.net/npm/chart.js@3.6.0/dist/chart.min.js"></script>
</body>

Related