我试图弄清楚在指定数据集时如何在 ChartJS 中使用 yAxisKey
选项,但是在重现 this example 时遇到了问题从文档。我尝试搜索涉及 yAxisKey
(或 xAxisKey
)、parsing
选项以及有关指定 datasets的一般信息的问题
,但不幸的是到目前为止是空白的。
示例
<!doctype html>
<html>
<head>
<title>Example Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const data = [{x: 'Jan', net: 100, cogs: 50, gm: 50}, {x: 'Feb', net: 120, cogs: 55, gm: 75}];
const config = {
type: 'bar',
data: {
labels: ['Jan', 'Feb'],
datasets: [{
label: 'Net sales',
data: data,
parsing: {
yAxisKey: 'net'
}
}, {
label: 'Cost of goods sold',
data: data,
parsing: {
yAxisKey: 'cogs'
}
}, {
label: 'Gross margin',
data: data,
parsing: {
yAxisKey: 'gm'
}
}]
},
};
window.onload = function() {
const ctx = document.getElementById('canvas').getContext('2d');
let chart = new Chart(ctx, config);
};
</script>
</body>
</html>
这会为我生成一个看起来很空的图表。
我是否遗漏了一些明显的东西?对语法有误解?
提前致谢!
最佳答案
由于您当前使用的 Chart.js 版本 2.8.0 中尚不提供 per-dataset parsing
选项,因此您仍然可以通过 Array.map()
获得相同的结果。功能。
请查看您修改后的代码,看看它是如何工作的。
<!doctype html>
<html>
<head>
<title>Example Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const data = [
{ x: 'Jan', net: 100, cogs: 50, gm: 50 },
{ x: 'Feb', net: 120, cogs: 55, gm: 75 }
];
const config = {
type: 'bar',
data: {
labels: data.map(o => o.x),
datasets: [{
label: 'Net sales',
data: data.map(o => o.net)
}, {
label: 'Cost of goods sold',
data: data.map(o => o.cogs)
}, {
label: 'Gross margin',
data: data.map(o => o.gm)
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
};
window.onload = function() {
const ctx = document.getElementById('canvas').getContext('2d');
let chart = new Chart(ctx, config);
};
</script>
</body>
</html>
关于javascript - 如何使用 Chart.js 指定 "per dataset"解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63511006/