如何为Chart.js数据集中的指定数据点分配yAxisID?
问题描述
我拥有如下数据集:
[ {data: [100, 50, 0.5], backgroundColor:'#506f86', borderColor: '#506f86', hoverBackgroundColor:'#384e5e', hoverBorderColor: '#384e5e', label: 'Service'}, {data: [80, 20, 0.25], backgroundColor:'#9ec5fe', borderColor: '#9ec5fe', hoverBackgroundColor:'#6ea8fe', hoverBorderColor: '#6ea8fe', label: 'Maintenance'}, {data: [60, 20, 0.33], backgroundColor:'#ffc107', borderColor: '#ffc107', hoverBackgroundColor:'#cc9a06', hoverBorderColor: '#cc9a06', label: 'Monitoring'} ]
数据点对应含义:
data[0] - 销售额(Sales) data[1] - 毛利金额(Gross Profit $) data[2] - 毛利率(Gross Profit %)
已定义的坐标轴配置:
scales: { dollar: { type: 'linear', position: 'left', ticks: { callback: (label, index, labels) => { return `$ ${label}`; } } }, percent: { type: 'linear', position: 'right', grid: { display: false, }, ticks: { color: '#de703c', callback: function(value, index, values) { return (value + '%'); } } }, xAxis: { type: 'category', axis: 'x', labels: ['销售额', '毛利金额', '毛利率'], }, },
我希望将数据集中的第三个数据点“毛利率”映射到右侧yAxisID为“percent”的坐标轴,该如何实现?
实现方案
要让单个数据集中的不同数据点对应不同y轴,核心是把原来的一维数值数组改成带坐标轴标识的对象数组,每个数据点通过yAxisID指定对应的坐标轴。具体操作如下:
1. 修改数据集的data结构
将每个数据集的data从纯数值数组,替换为包含y值和yAxisID的对象数组,前两个数据点绑定左侧dollar轴,第三个绑定右侧percent轴:
[ { data: [ {y: 100, yAxisID: 'dollar'}, {y: 50, yAxisID: 'dollar'}, {y: 0.5, yAxisID: 'percent'} ], backgroundColor:'#506f86', borderColor: '#506f86', hoverBackgroundColor:'#384e5e', hoverBorderColor: '#384e5e', label: 'Service' }, { data: [ {y: 80, yAxisID: 'dollar'}, {y: 20, yAxisID: 'dollar'}, {y: 0.25, yAxisID: 'percent'} ], backgroundColor:'#9ec5fe', borderColor: '#9ec5fe', hoverBackgroundColor:'#6ea8fe', hoverBorderColor: '#6ea8fe', label: 'Maintenance' }, { data: [ {y: 60, yAxisID: 'dollar'}, {y: 20, yAxisID: 'dollar'}, {y: 0.33, yAxisID: 'percent'} ], backgroundColor:'#ffc107', borderColor: '#ffc107', hoverBackgroundColor:'#cc9a06', hoverBorderColor: '#cc9a06', label: 'Monitoring' } ]
2. 确保坐标轴配置显式声明ID
虽然你的坐标轴配置中键名默认就是轴ID,但显式声明id字段能避免潜在的识别问题,修改后的坐标轴配置如下:
scales: { dollar: { id: 'dollar', type: 'linear', position: 'left', ticks: { callback: (label, index, labels) => { return `$ ${label}`; } } }, percent: { id: 'percent', type: 'linear', position: 'right', grid: { display: false, }, ticks: { color: '#de703c', callback: function(value, index, values) { return (value + '%'); } } }, xAxis: { type: 'category', axis: 'x', labels: ['销售额', '毛利金额', '毛利率'], }, },
完成以上修改后,每个数据集的前两个数据点会自动对应左侧的金额坐标轴,第三个数据点则对应右侧的百分比坐标轴,实现你需要的映射效果。
内容的提问来源于stack exchange,提问作者Ashish Singh
相关产品推荐
相关产品推荐

