2

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'
uwe
  • 3,938
  • 11
  • 37
  • 50

1 Answers1

3

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>
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
  • released today! I guess my question couldn't have been better timed ;-) Thanks a bunch – uwe Oct 23 '21 at 19:52