how to change color of bar if its goes above avg score in mixed graph chart.js

Shubham Singh :

img of graph that i have created

In this reference picture, I want to change color to green of bar if it goes above AvgScor that is line bar

I am using chart.js mixed graph

in this img 4th one from the left is above avg score

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

var totalScoreData = [60,30,50,75,45,41]; // Add data values to array
var averageData = [61,45,55,70,46,52] // Add data values to array
var labels = ["A"," Q", "C","C","A","p"]; // Add labels to array

var overAllScore = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: labels,
      datasets: [{
        label: 'Scores', // Name the series
        data: totalScoreData,
        backgroundColor: 'rgba(255, 99, 132, 0.2)',

        borderWidth: 1 
      },
          {
        label: 'AvgScore',
        data: averageData, 
        backgroundColor: '#f443368c',
        borderColor: '#f443368c',

        borderWidth: 1, // Specify bar border width
        type: 'line', 
        fill: false        
      }]
    },
    options: {
    responsive: true, // Instruct chart js to respond nicely.
    maintainAspectRatio: false,
    scales: {
      yAxes: [{
          display: true,
          ticks: {
            beginAtZero: true,
            steps: 10,
            max: 100
          }
        }]
    }

    }

  });
<canvas id="overAllScore" style="display: block; width: 765px; height: 382px;" width="765" height="382" class="chartjs-render-monitor"></canvas>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

Alex L :

Ok let's put together a minimal reproducible example first (in the question, make sure to have code that someone can either click "run code snippet" here or open a link to a codePen / code Sandbox etc. - you should give the dummy data to allow others to get started right away with an example just like you have it in your screenshot etc.):

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

var totalScoreData = [60,30,50,75,45,41]; // Add data values to array
var averageData = [61,45,55,70,46,52] // Add data values to array
var labels = ["A"," Q", "C","C","A","p"]; // Add labels to array

function colorGenerator() {
  return totalScoreData.map((child,index) => {
    if (child >= averageData[index]){
      return 'rgba(5, 250, 10, 0.2)'
    } else {
       return 'rgba(255, 99, 132, 0.2)'
    }
  })
} 

var overAllScore = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Scores', // Name the series
                data: totalScoreData,
                backgroundColor: colorGenerator, //set the colors with a function
                borderWidth: 1 
            },
            {
                label: 'AvgScore',
                data: averageData, 
                backgroundColor: '#f443368c',
                borderColor: '#f443368c',

                borderWidth: 1, // Specify bar border width
                type: 'line', 
                fill: false        
            }]
        },
        options: {
        responsive: true, // Instruct chart js to respond nicely.
        maintainAspectRatio: false,
        scales: {
            yAxes: [{
                    display: true,
                    ticks: {
                        beginAtZero: true,
                        steps: 10,
                        max: 100
                    }
                }]
        }

        }

    });
    
    ///from chart.js docs:
    /*
    var chartData = {
			labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
			datasets: [{
				type: 'line',
				label: 'Dataset 1',
				borderColor: window.chartColors.blue,
				borderWidth: 2,
				fill: false,
				data: [
					1,2,3,4,5,6,7
				]
			}, {
				type: 'bar',
				label: 'Dataset 2',
				backgroundColor: window.chartColors.red,
				data: [
					2,3,4,5,6,7,8
				],
				borderColor: 'white',
				borderWidth: 2
			}]

		};
		window.onload = function() {
			var ctx = document.getElementById('canvas').getContext('2d');
			window.myMixedChart = new Chart(ctx, {
				type: 'bar',
				data: chartData,
				options: {
					responsive: true,
					title: {
						display: true,
						text: 'Chart.js Combo Bar Line Chart'
					},
					tooltips: {
						mode: 'index',
						intersect: true
					}
				}
			});
		};
    */
<canvas id="overAllScore" style="display: block; width: 765px; height: 382px;" width="765" height="382" class="chartjs-render-monitor"></canvas>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

Next, we can figure out a way to change the color of the bar based on its value and the average value.

The result is this:

enter image description here

And to achieve this we needed to do the following:

Firstly, set up the two data arrays:

var totalScoreData = [60,30,50,75,45,41];
var averageData = [61,45,55,70,46,52]

Then modify the new Chart constructor:

var overAllScore = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Scores', // Name the series
                data: totalScoreData,
                backgroundColor: colorGenerator, //set the colors with a function
                borderWidth: 1 
            },
            {
                label: 'AvgScore',
                data: averageData, 
                backgroundColor: '#f443368c',
                borderColor: '#f443368c',

                borderWidth: 1, // Specify bar border width
                type: 'line', 
                fill: false        
            }]
        }, ...

The key line to notice here is backgroundColor: colorGenerator, for the scores dataset. This means assign the colors based on a function.

This function looks like this:

function colorGenerator() {
  return totalScoreData.map((child,index) => {
    if (child >= averageData[index]){
      return 'rgba(5, 250, 10, 0.2)' //green
    } else {
       return 'rgba(255, 99, 132, 0.2)' //red
    }
  })
} 

What it does is take the totalScoreData array and map over it, wherever it is above the corresponding average data at the same index - averageData[index] then return a green color, otherwise return the red color.

That's it :)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=302331&siteId=1