javascript - 如果条形图高于混合图表 Chart.js 中的平均分数,如何更改条形图的颜色

标签 javascript html css chart.js

img of graph that i have created

在此引用图片中,如果条形高于 AvgScor(即线形条),我想将其颜色更改为绿色

我正在使用chart.js混合图

在此图片中,左起第四个高于平均分数

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/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5132393023257f3b2211637f697f61" rel="noreferrer noopener nofollow">[email protected]</a>"></script>

最佳答案

好吧,让我们首先整理一个最小的可重现示例(在问题中,确保有人可以单击此处的“运行代码片段”或打开指向 codePen/代码沙箱等的链接)的代码 - 您应该给出虚拟数据,以允许其他人立即开始使用示例,就像您的屏幕截图中的示例一样):

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/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a39323b282e7430291a687462746a" rel="noreferrer noopener nofollow">[email protected]</a>"></script>

接下来,我们可以想出一种根据条形的值和平均值来改变条形颜色的方法。

结果是这样的:

enter image description here

为了实现这一目标,我们需要执行以下操作:

首先,设置两个数据数组:

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

然后修改新的 Chart 构造函数:

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        
            }]
        }, ...

这里要注意的关键行是分数数据集的 backgroundColor: colorGenerator,。这意味着根据函数分配颜色。

这个函数看起来像这样:

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
    }
  })
} 

它的作用是获取totalScoreData数组并对其进行映射,无论它位于同一索引处的相应平均数据之上 - averageData[index],然后返回绿色,否则返回红色。

就是这样:)

关于javascript - 如果条形图高于混合图表 Chart.js 中的平均分数,如何更改条形图的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60666936/

相关文章:

background-color - 具有圆 Angular 和重叠背景颜色的 CSS 选择

javascript - Angular 2在重定向后保留URL的状态

php - 表格中断 html php,php 的发票报告

javascript - 从文本元素获取小数

javascript - HTML5 视频无法在 Android 上播放

css - 覆盖的 z-index 问题

php - 如何用 if 条件解决 JavaScript 中的 setTimeout 问题?

javascript - 如何根据两个变量获取变量值

javascript - 如何使用每个对象的所有属性来过滤对象数组以检查匹配项?

css - 如果两个元素都存在于同一级别,则切换规则 - SCSS