使用chart.js显示数组中的多个数据集

时间:2018-09-15 12:39:11

标签: javascript json ajax chart.js

我试图显示有关一个国家不同部门人口增长的折线图,但是当我从PHP获取JSON时,无法迭代该数组以获取年份和总数。人口。这是我的代码:

$(document).ready(function(){

 $.ajax({

   url: "../assets/api/stats.php",

   data: "stat=birth&in=departement",

   type: "GET",

   success: function(data) {
      console.log(data);
      var departement = {
             Zone: []
      };

      var year = {
             Birth: []
      };

      var total = {
             Birth: []
      };

      var len = data.length;
      console.log(data.length);

      var lctx = $('#line-chart- departement');
      for (var j = 0; j < len; j++) {

     departement.Zone.push(data[j][0].departement);

     for (var i = 0; i < data.length; i++) {
       annee.Naissance.push(departement.Zone[i].annee);
       total.Naissance.push(departement.Zone[i].total);
     }

     var data = {
       labels: annee.Naissance,
       datasets: [{
         label: data[j],
         data: total.Naissance,
         backgroundColor: getRandomColor(),
         borderColor: "#3e95cd",
         fill: false,
         lineTension: 0,
         pointRadiues: 5
       }]
     };
     console.log();
     var chart = new Chart(lctx, {
       type: "line",
       data: data,
       options: {}
     });

   }
 },error: function(data) {
   //console.log(data)
 }
   });
   function getRandomColor() {

   var letters = '0123456789ABCDEF'.split('');
   var color = '#';
   for (var i = 0; i < 6; i++) {
   color += letters[Math.floor(Math.random() * 16)];
 }

 return color;}
 });

还有我的数组

[

    {
        "Nord-Est": 
       [
            {
                "annee": "1995",
                "totalnaissance": "1"
            }
        ]
    },
    {
        "Ouest": 
        [
            {
                "annee": "1994",
                "totalnaissance": "2"
            },
            {
                "annee": "1995",
                "totalnaissance": "1"
            }
        ]
    },
    {
        "Nippes": 
        [
            {
                "annee": "1951",
                "totalnaissance": "1"
            },
            {
                "annee": "1987",
                "totalnaissance": "1"
            },
            {
                "annee": "1986",
                "totalnaissance": "1"
            },
            {
                "annee": "1992",
                "totalnaissance": "2"
            }
        ]
    },
    {
        "Sud-Est": 
        [
            {
                "annee": "1985",
                "totalnaissance": "1"
            }
        ]
    }
]

1 个答案:

答案 0 :(得分:2)

事实证明,这不仅仅是“见面而已”。

  • 由于我们需要所有年份作为x轴,因此我们需要遍历两次数据-一次获取所有年份,一次获取每年的数据。如果没有该年的数据,我们必须输入null。否则,x和y点将不匹配。
  • 获取所有年份之后,必须按升序对其进行排序,并且我们需要以相同的顺序获取totalnaissance数据。
  • 您已给borderColor设置了固定值#3e95cd,但对于折线图,边框颜色是线条颜色。所以我改变了。我也将backgroundColor“透明”和pointBackgroundColor设为borderColor

我已经创建了Pen

<canvas id="myChart" width="500" height="500"></canvas>
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var data = {
      Nippes: [
        {
          annee: "1951",
          totalnaissance: "1"
        },
        {
          annee: "1986",
          totalnaissance: "1"
        },
        {
          annee: "1987",
          totalnaissance: "1"
        },
        {
          annee: "1992",
          totalnaissance: "2"
        }
      ],
      "Nord-Est": [
        {
          annee: "1995",
          totalnaissance: "1"
        }
      ],
      Ouest: [
        {
          annee: "1994",
          totalnaissance: "2"
        },
        {
          annee: "1995",
          totalnaissance: "1"
        }
      ],
      "Sud-Est": [
        {
          annee: "1985",
          totalnaissance: "1"
        }
      ]
    };
var departments = [];
var annees = [];

for (var department in data) {
    if (data.hasOwnProperty(department)) {
        var departmentData = data[department];
        getYears(departmentData);
    }
}

annees.sort();

for (var department in data) {
    if (data.hasOwnProperty(department)) {
        var departmentData = data[department];//getDataForDepartment(i);
        var totalnaissanceData = getTotalNaissanceDataForDep(departmentData);

        var departmentObject = prepareDepartmentDetails(department, totalnaissanceData);
        departments.push(departmentObject);
    }
}

var chartData = {
    labels: annees,
    datasets : departments
};

var chart = new Chart(ctx, {
   type: "line",
   data: chartData,
   options: {}
 });




function getDataForDepartment(index){
    return data[i][Object.keys(data[i])[0]];
}

function getYears(departmentData){
    for (var j = 0; j< departmentData.length; j++){
        if (!annees.includes(departmentData[j].annee)){
            annees.push(departmentData[j].annee);
        }
    }
}

function getTotalNaissanceDataForDep(departmentData){
    var totalnaissanceData = [];
    for (var j = 0; j < annees.length; j++){
        var currentAnnee = annees[j];
        var currentTotalNaissance = null;
        for (var k = 0; k< departmentData.length; k++){
            if (departmentData[k].annee === currentAnnee){
                currentTotalNaissance = departmentData[k].totalnaissance;
                break;
            }
        }
        totalnaissanceData.push(currentTotalNaissance);
    }
    return totalnaissanceData;
}

function prepareDepartmentDetails(departmentName, totalnaissanceData){
    var dataColor = getRandomColor();
    return {
        label : departmentName,
        data : totalnaissanceData,
        backgroundColor: 'transparent',
        borderColor: dataColor,//"#3e95cd",
        pointBackgroundColor : dataColor,
        fill: false,
        lineTension: 0,
        pointRadius: 5
    }
}

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
</script>