Charts.js - Bar chart different colors for value intervals not working

Viewed 153

I'm reading some data from an JSON and I am plotting the values vs time using Charts.js. However, I cannot manage to solve two things:

  1. I cannot read the last only 20 elements
  2. I cannot manage to make the bar change colors depending on the values

Regarding 1, I have managed to read the first 20 elements using return key<20;, but I don't know how to read the last elements. I have tried with return [key.length-1,key.length-20], but doesn't really work. Regarding 2, I have tried different methods that some other people encountered and some codes from Fiddle, but it doesn't work. The console shows the elements in chartColors. Can anyone help me with these two issues?

The code below works just fine and give this: enter image description here

And I would like something like this: enter image description here

<!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)
        {
            $.each(meteo, function(key, value){
                dataPoints1.push({x: value[0], y: value[9]});
                //How to make this array write the last 20 elements, and not the first 20, like it is now
                return key<20;
            });
            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: chartColors.blue,
                        borderColor: "red",
                        fill: true,
                        responsive: true
                    },
                    ]}
                });
                var dataset = PM25.data.datasets[0];                
                for(i=0;i<dataset.data.length;i++){
                    var color="green";
                    if(dataset.data[i].value>40){
                        dataset.backgroundColor[i] = red;
                    }
                    else if(dataset.data[i].value>60){
                        dataset.backgroundColor[i] = blue;
                    }
                    console.log(dataset.backgroundColor[i])
                }
                
                PM25.update();
                
                
            })}
        </script>
        </html>

1 Answers

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>

Related