chart.js条形图根据值更改颜色 [英] chart.js bar chart change color based on value

查看:54
本文介绍了chart.js条形图根据值更改颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案

给出一个名为数据"的 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>

这篇关于chart.js条形图根据值更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆