その混合グラフchart.jsで平均スコア以上になる場合はバーの色を変更する方法

Shubhamシン:

私が作成したことをグラフのIMG

この参照画像では、私はそれはラインバーであることAvgScor以上になる場合は、バーの緑に色を変更したいです

私はchart.jsに混合グラフを使用しています

このIMGの左から4番目の1は、平均スコアを上回っています

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>

アレックス・L:

あなたはダミーデータを与える必要があります - 大丈夫だが、問題の(最初に一緒に最小限の再現性の例を置く誰かがここでも「実行コードスニペット」をクリックするか、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/[email protected]"></script>

次に、我々はその値と平均値に基づいてバーの色を変更する方法を見つけ出すことができます。

結果はこれです:

ここでは、画像の説明を入力します。

そして、これを実現するために、我々は次のことを行うために必要な:

まず、二つのデータ列を設定します。

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

次に、新しいチャートのコンストラクタを変更します。

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]、次に緑色を返し、そうでない場合は赤色を返します。

それでおしまい :)

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=303347&siteId=1