[Chartjs]-Charts.js – Bar chart different colors for value intervals not working

1πŸ‘

βœ…

For the borderColor to show you need to set the borderWidth to a value bigger then 0, to get the last 20 values you can use a for loop and start 20 values before the end. As last for the different collor bars you can use a scribtable option.

Example:

<!DOCTYPE HTML>
<html>

<head>

</head>

<body>
  <canvas id="PM25">test</canvas>

</body>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4"></script>

<script type="text/javascript">
  var pm25 = document.getElementById('PM25').getContext('2d');

  window.onload = function() {
    var dataPoints1 = [];
    $.getJSON("https://checkup-7b62e.firebaseio.com/meteo_radauti.json", function(meteo) {
      for (i = meteo.length - 20; i < meteo.length; i++) {
        dataPoints1.push({
          x: meteo[i][0],
          y: meteo[i][9]
        });
      }

      var chartColors = {
        red: 'rgb(255, 99, 132)',
        blue: 'rgb(54, 162, 235)'
      };

      var PM25 = new Chart(pm25, {
        type: 'bar',
        data: {
          labels: dataPoints1.map(x => x.x),
          datasets: [{
            data: dataPoints1.map(y => y.y),
            label: 'PM2.5 (ppm)',
            backgroundColor: (ctx) => (ctx.dataset.data[ctx.dataIndex] > 60 ? chartColors.blue : ctx.dataset.data[ctx.dataIndex] > 40 ? chartColors.red : "green"),
            borderColor: chartColors.red,
            borderWidth: 1
          }, ]
        }
      });
    })
  }
</script>

</html>

Leave a comment