简体   繁体   中英

Problem to create dynamic pie chart in ChartJS

I am creating a dynamic Pie chart with the ChartJS Library. I am using Laravel 6 and in my controller I have the function that passes an array in JSON Format. This is the structure of the array:

[
{"label":"assistingSales","values":21},
{"label":"hseMeeting","values":12},
{"label":"training","values":30}
]

In my .js file I retrieve this data using JQuery and the .GET Method, and then I use a forEach Loop to create two arrays: Values and Labels . I send these arrays to the web console (console.log), and they appear both right. The values are integers and the labels are strings. The problem begins when I set these arrays as the dataset and labels for the Pie Chart in the .js file. If I write the values manually in the dataset, the Pie displays fine, but it can't recognize the array itself.

This is the code for the .js file

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);
  });
});

The problem is that the Chart doesn't appear when I set the arrays as datasets and labels . It appears only if I set them this way:

valores[0],valores[1],valores[2]
etiquetas[0],etiquetas[1],etiquetas[2]

I thought it could be related to the datatypes, but they are ok, Integers and Strings. I also tried using a for-loop to create the two separate arrays, but nothing happened.

Can you please check my code and tell me if there is some other or better way to do it? Thanks in advance!

The problem is that you wrap valores and etiquetas arrays in another array inside the config .

data: [ valores ]
labels: [ etiquetas ]

Just get rid of these sqare brackets and it will work.

data: valores
labels: etiquetas

Pleas have a look at the following runnable code snippet.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM