chart.js bar chart change color based on value(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?
推荐答案
给定一个名为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>
这篇关于chart.js 条形图根据值改变颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:chart.js 条形图根据值改变颜色
基础教程推荐
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
