chart.js 条形图根据值改变颜色根据、颜色、条形图、chart

2023-09-07 11:49:58 作者:凉城梦境空人心

function argMax(array) {
  return array.map((x, i) => [x, i]).reduce((r, a) => (a[0] > r[0] ? a : r))[1];
}

// dummy data
var data = [12, 19, 1, 14, 3, 10, 9];
var labels = data.map((x, i) => i.toString()); 

// other data color
var color = data.map(x => 'rgba(75,192,192,0.4)');

// change max color
color[argMax(data)] = 'red';

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                    label: 'value',
                    data: data,
                    backgroundColor: color,
            }]
        }
});

大家好.我在 Chart.js 中找到了这段代码最大值栏 这个论坛.但我不知道如何更改它以显示最大的三个值.

Hey Guys. I found this code in Chart.js changing the color of the max value bar this forum. But i don't have a clue how to change it to show me the biggest three values.

如何更改此代码以不同颜色显示最大的三个值?

How can i change this code to show me the biggest three values in a different color?

推荐答案

给定一个名为data"的 number 值的 array,您可以从中创建一个排序数组.然后你 map 原始数据的值,根据其在已排序 array 中的位置返回适当的颜色.

Given an array of number values named "data", you create a sorted array out of it. Then you map the values of the original data, returning the appropriate color depending on its position in the sorted array.

const backgroundColors = data.map(v => sortedData.indexOf(v) >= data.length - 3 ? 'red' : 'green');

请查看下面的可运行代码示例.

Please have a look at the runnable code sample below.

const labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O'];
const data = labels.map(l => Math.floor(Math.random() * 1000) + 1);
const sortedData = data.slice().sort((a, b) => a - b);
const backgroundColors = data.map(v => sortedData.indexOf(v) >= data.length - 3 ? 'red' : 'green');

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: {
    labels: labels,
    datasets: [{
      label: "My Dataset",
      data: data,
      backgroundColor: backgroundColors
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>