javascript - 如何在chartjs中为同一组数据添加多个标签?
问题描述
我正在制作一个简单的仪表板,其中有一个显示公司订单数量的条形图。它显示了过去一周每天订购的数量、今天的数量以及接下来几天的预定订单数量。
我正在使用颜色来区分这 3 个时刻中的每一个,但我找不到拥有 3 个标签的解决方案,每个标签都有正确的颜色(“上周”为蓝色,“今天”为橙色,“预定”为灰色)。
解决方案
您可以为此使用该generateLabels
功能:
var options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1,
backgroundColor: ['lightblue', 'lightblue', 'lightblue', 'orange', 'orange', 'gray']
}]
},
options: {
plugins: {
legend: {
labels: {
generateLabels: () => {
return [{
datasetIndex: 0, // Since its all 1 dataset just hide if it gets clicked, remove this line for legend click to do nothing
text: 'Last week',
fillStyle: 'lightBlue',
strokeStyle: 'lightBlue'
},
{
datasetIndex: 0, // Since its all 1 dataset just hide if it gets clicked, remove this line for legend click to do nothing
text: 'Today',
fillStyle: 'orange',
strokeStyle: 'orange'
},
{
datasetIndex: 0, // Since its all 1 dataset just hide if it gets clicked, remove this line for legend click to do nothing
text: 'Scheduled',
fillStyle: 'grey',
strokeStyle: 'grey'
}
];
}
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
推荐阅读
- function - 如何在负载中收集函数返回
- android - Android“存储”和“重用”获取的URI
- javascript - 反应:您可能忘记从定义它的文件中导出组件,或者您可能混淆了默认和命名导入
- elasticsearch - 使用 SSL 调用 ElasticSearch
- rest - 获取 AAD 组的 SubjectDescriptor
- bash - 为什么我的正则表达式匹配子字符串而不是完整字符串?
- scala - 异常检测 Deequ 库中的直方图
- scanf - 在 scanf() 之后使用 Puts() 和 Gets() 不起作用
- ruby - 如何检查用户输入是否包含数字?在红宝石
- ajax - 无法使用 AJAX 和 AWS API Gateway 发布到 AWS Lambda 函数