How to ignore points with same value in chart.js?

by darrion.kuhn , in category: Javascript , 10 months ago

How to ignore points with same value in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 10 months ago

@darrion.kuhn 

To ignore points with the same value in Chart.js, you can use the pointBackgroundColor option along with a custom function. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var chartData = {
  labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
  datasets: [{
    label: 'Values',
    data: [7, 3, 7, 2, 5, 5, 5],
    backgroundColor: 'rgba(0, 123, 255, 0.5)',
    borderColor: 'rgba(0, 123, 255, 1)',
    pointBackgroundColor: function(context) {
      var index = context.dataIndex;
      var value = context.dataset.data[index];
      return value === context.dataset.data[index - 1] ? 'transparent' : 'rgba(0, 123, 255, 0.5)';
    }
  }]
};

var chartOptions = {
  responsive: true,
  scales: {
    y: {
      beginAtZero: true
    }
  }
};

var chart = new Chart(document.getElementById('myChart'), {
  type: 'line',
  data: chartData,
  options: chartOptions
});


In this example, we define the pointBackgroundColor using a function that checks if the current value is the same as the previous value. If they are the same, we set the color to transparent, otherwise, we set it to the desired color. This ensures that points with the same value are not displayed in the chart.