Chartjs-How to make bars change color based on value in chartsjs

0๐Ÿ‘

Iโ€™ve pulled the example from the chart.js website and made a little demo.

I utilized the map function which you can check out here

Hopefully this is what you asked for and I found some little flaws in your request.

If you want 11 to be displayed in orange you need to check it before
x > 10 as this will return true.

Also if you check x > 10, x < 10 10 it self will have no case (I added a default black color for such cases in my code ๐Ÿ™‚ ).

DEMO:

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script>

<canvas id="myChart" width="400" height="100"></canvas>
<script>
const dataset = [12, 19, 11, 3, 5, 2, 3, 10];

let ctx = document.getElementById('myChart').getContext('2d');
let myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: dataset.map(e => `Label: ${e}`),
        datasets: [{
            label: '# of Votes',
            data: dataset,
            backgroundColor: dataset.map(e => {
              if(e === 11) return 'orange';			// You need to check orange first as > 10 will be true and give it a green color
							if(e > 10) return 'green';
              if(e < 10) return 'red';
              return 'black';										// Return black in case nothing fits but that shouldn't be the case as 
              																	// every value is either smaller or bigger than 10... except 10 sooo :D

            }),
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});
</script>

In your Case:

const dataset = [4, 7, 3, 6, 10, 7, 4, 6, 3, 5, 6, 7, 3, 14, 6, 7, 7, 2, 5, 6, 7,4, 9, 8, 3, 2, 8, 7, 3, 15, 6, 7, 3, 5, 6, 7, 7, 2, 5, 6];
datasets: [

{
  label: "Voltage",
  backgroundColor: "lightgreen",
  borderColor: dataset.map(e => {
    if(e === 1) return 'orange';
    if(e > 10) return 'green';
    if(e < 10) return 'red';
    return 'black';

  }),
  borderWidth: 1,
  data: dataset,

},


]

Leave a comment