我有一个使用 Laravel 的 PHP 应用程序,并且我有两个数组必须加入到一个图表中。两者都显示每月的数量。我可以编写一个标签,如文档所示的正常用例,但两行不一定包含相同数量的月份,因此我想将每个 y 轴数字与其特定月份标签相关联。
var ctx = document.getElementById('flujomes');
var entregas = @json($ar_entregas);
var reversas = @json($ar_reversas);
console.log(entregas);
console.log(reversas);
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: "Número de entregas",
data: entregas,
backgroundColor: [
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
],
borderWidth: 1
},
{
label: "Número de reversas",
data: reversas,
backgroundColor: [
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(54, 162, 235, 1)'
],
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
responsive: true,
maintainAspectRatio: false,
}
});
但是它并没有像我预期的那样工作:
因此,chart.js 获取了数据,但它不知道 x 点实际在哪里。
最佳答案
问题是库不知道谁来处理您提供的x
值,只有当您使用线性轴(数字数据)时它才能够做到这一点无需其他选项即可正确。
有两种方法可以解决这个问题
选项 1 - 定义类别
轴
由于您知道标签上的值,因此可以使用 type: 'category'
设置它们,因此库知道正确放置点的位置,如下例所示:
var chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: "Data 1",
data: [{
x: '2018-2',
y: 98
}, {
x: '2018-4',
y: 74
}, {
x: '2018-5',
y: 52
}],
}, {
label: "Data 2",
data: [{
x: '2018-3',
y: 25
}, {
x: '2018-5',
y: 52
}],
}]
},
options: {
scales: {
xAxes: [{
type: 'category',
labels: ['2018-2', '2018-3', '2018-4', '2018-5']
}]
},
tooltips: {
mode: 'x',
callbacks: {
title: function(tooltipItems, data) {
let tI = tooltipItems[0];
return data.datasets[tI.datasetIndex].data[tI.index].x;
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>
选项 2 - 将标签转换为日期
另一种可能的解决方案是将标签从文本转换为 Date()
,其中包含 moment("2018-2")
之类的时刻,然后设置一个 min
和 max
作为 ticks
值,以及显示格式,例如:
xAxes: [{
type: 'time',
time: {
displayFormats: {
quarter: 'YYYY-MM'
}
}
}]
总的来说,这是一个更复杂的解决方案。
更新 - 修复错误的工具提示标题
正如前面提到的,第一个解决方案将导致当用户悬停在某个点时,工具提示的标题将与 x
标签不同,这是因为该点带有错误的 index
值(此索引
用于返回标签位置)。
在尝试解决此问题时,由于 Scatter
图表创建了与我们想要实现的结果类似的结果,因此我已锁定此类型的 Controller here ,但运气不好,因为在这种情况下,或者标题被忽略,或者值也错误。
所以我想出的是这样的:
tooltips: {
mode: 'x', // optional
callbacks: {
title: function(tooltipItems, data) {
let tI = tooltipItems[0];
return data.datasets[tI.datasetIndex].data[tI.index].x;
}
}
}
基本上,它不会搜索标签数组中的索引,而是获取原始的 x
数据值。
关于javascript - 如何使用 Chart.js 制作带有关联数组的图表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56045882/