3

I'm trying to display a multiple line chart of about the growth of the population on the different department of a country but when I get the JSON from PHP I can't iterate the array for getting the year and total of the population. Here's my code:

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

And there is my array

[

    {
        "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"
            }
        ]
    }
]
4
  • What are the lines you want for the chart? annee and totalnaissance? Commented Sep 15, 2018 at 13:30
  • Or you want lines for each department? And then annee and totalnaissance will be your x and y axis Commented Sep 15, 2018 at 13:32
  • I also need a line for each department this why I did a function random color for each line Commented Sep 15, 2018 at 14:10
  • Exactly I need a line for each department, annee and totalnaissance will be respectively my x and y axis Commented Sep 15, 2018 at 14:29

1 Answer 1

3

That turned out to be 'more than meets the eye'.

  • Since we need all the years as x axis, we need to go through the data twice - once to get all the years, once to get the data for each year. If data is not available for that year, we have to enter null. Otherwise the x and y points get mismatched.
  • After all the years are fetched, they have to be sorted in ascending order, and we need to get the totalnaissance data in the same order.
  • You had given the borderColor a fixed value of #3e95cd, but for a line chart a border color IS the line color. So I've changed that. I've also made the backgroundColor 'transparent' and pointBackgroundColor equal to borderColor.

I've created a 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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.