[Chartjs]-Display multiple datasets from array with chart.js

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>

Leave a comment