[英]How to make a chart with an associative array with chart.js?
我有一個使用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
值,只有在使用線性軸(數字數據)的情況下,它才能正確執行此操作而無需其他選擇。
有兩種解決方法,
category
軸 因為您知道標簽上將要包含的值,所以可以將其設置為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>
另一個可能的解決方案是將帶有文本標簽的文本從文本轉換為Date()
,例如moment("2018-2")
,然后將min
和max
設置為ticks
值,並設置顯示格式,例如:
xAxes: [{
type: 'time',
time: {
displayFormats: {
quarter: 'YYYY-MM'
}
}
}]
總體而言,這是一個更復雜的解決方案。
如前所述,當用戶將鼠標懸停在一個點上時,第一種解決方案將導致工具提示的標題與x
標簽不同,這是因為該點帶有錯誤的index
值(此index
用於返回標簽位置)。
在嘗試解決此問題時,由於Scatter
與我們嘗試實現的結果類似,因此我在這里鎖定了這種類型的控制器,但是沒有運氣,因為在這種情況下或標題被忽略或價值也是錯誤的。
所以我想到的是這樣的:
tooltips: {
mode: 'x', // optional
callbacks: {
title: function(tooltipItems, data) {
let tI = tooltipItems[0];
return data.datasets[tI.datasetIndex].data[tI.index].x;
}
}
}
基本上,而不是在標簽數組中搜索索引,它將獲得原始的x
數據值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.