[Chartjs]-How to change the color of Chart.js points depending on the label

12👍

You can give an array of colors to pointBackgroundColor property:

var ctx = document.getElementById('lineChart').getContext('2d');

var colors = ["rgba(255,0,0,1)", "rgba(0,255,0,1)", "rgba(0,0,255,1)", "rgba(255,0,0,1)", "rgba(0,255,0,1)"];
var colors1 = Object.assign([], colors);
colors1.sort();
var data = {
  labels: [
    "1 ",
    "2 ",
    "3 ",
    "4 ",
    "5 ",
  ],
  datasets: [{
    label: "line 1",
    strokeColor: "rgba(151,187,205,1)",
    pointRadius: 5,
    pointBackgroundColor: colors,
    fill: false,
    data: [
      0.33771896,
      0.903282737,
      0.663260514,
      0.841077343,
      0.172840693,

    ],
  }, {
    label: "Average",
    strokeColor: "rgba(245, 15, 15, 0.5)",
    pointBackgroundColor: colors1,
    pointRadius: 5,
    fill: false,
    data: [0.70934844,
      0.562981612,
      0.496916323,
      0.410302488,
      0.55354621
    ]
  }]
};

var options = {
  datasetFill: false,
}
var myChart = new Chart(document.getElementById("lineChart"), {
  type: 'line',
  data,
  options
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<div>
  <canvas id="lineChart" width="600" height="200"></canvas>
</div>

Leave a comment