[英]Problem to create dynamic pie chart in ChartJS
我正在使用 ChartJS 庫創建一個動態餅圖。 我正在使用 Laravel 6,並且在我的控制器中,我具有以 JSON 格式傳遞數組的函數。 這是數組的結構:
[
{"label":"assistingSales","values":21},
{"label":"hseMeeting","values":12},
{"label":"training","values":30}
]
在我的 .js 文件中,我使用 JQuery 和 .GET 方法檢索這些數據,然后我使用 forEach 循環創建兩個數組: Values和Labels 。 我將這些數組發送到 Web 控制台 (console.log),它們看起來都正確。 值是整數,標簽是字符串。 當我將這些數組設置為 .js 文件中餅圖的數據集和標簽時,問題就開始了。 如果我在數據集中手動寫入值,則 Pie 顯示正常,但無法識別數組本身。
這是 .js 文件的代碼
var valores = new Array();
var etiquetas = new Array();
$(document).ready(function(){
$.get("http://127.0.0.1:8000/percentajes", function(response){
response.forEach(function(item){
valores.push(item.values);
etiquetas.push(item.labels);
});
console.log(valores);
console.log(etiquetas);
var config = {
type: 'pie',
data: {
datasets: [{
data: [ valores ],
label: 'Dataset 1'
}],
labels: [ etiquetas ]},
options: {
responsive: true,
legend: {
position: 'top',
},
animation: {
animateScale: true,
animateRotate: true
}
}
};
var ctx = document.getElementById('myPieChart').getContext('2d');
var mychart = new Chart(ctx, config);
});
});
問題是當我將數組設置為datasets和labels時沒有出現 Chart 。 只有當我這樣設置它們時才會出現:
valores[0],valores[1],valores[2]
etiquetas[0],etiquetas[1],etiquetas[2]
我認為這可能與數據類型有關,但它們沒問題,整數和字符串。 我還嘗試使用 for 循環來創建兩個單獨的數組,但什么也沒發生。
您能否檢查我的代碼並告訴我是否有其他或更好的方法來做到這一點? 提前致謝!
問題是您將valores
和etiquetas
數組包裝在config
中的另一個array
。
data: [ valores ]
labels: [ etiquetas ]
只需擺脫這些方括號,它就會起作用。
data: valores
labels: etiquetas
請查看以下可運行的代碼片段。
const response = [ {"label":"assistingSales", "values":21}, {"label":"hseMeeting", "values":12}, {"label":"training", "values":30} ] var valores = new Array(); var etiquetas = new Array(); response.forEach(function(item){ valores.push(item.values); etiquetas.push(item.label); }); var config = { type: 'pie', data: { datasets: [{ data: valores, backgroundColor: ['#FF6384', '#36A2EB','#FFCE56'] }], labels: etiquetas }, options: { responsive: true, legend: { position: 'top', }, animation: { animateScale: true, animateRotate: true } } }; new Chart(document.getElementById('myPieChart'), config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script> <canvas id="myPieChart"></canvas>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.