Displaying JSON data in Chartjs

后端 未结 2 1796
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 01:38

I am trying to use Chart JS to create a table with dynamically generated data points coming from my JSON file. The logic of my code looks like so:

var datapa         


        
2条回答
  •  遥遥无期
    2020-12-13 02:02

    I found the solution proposed by Bear GRiZZLY XI quite helpful. Makes use of the for.. loop.

    Let's suppose you have a json response from your api as follows:

    var markschart = document.getElementbyId("markschart");
    
    {
        "labels": "Maths,Geography,Physics,Chemistry,English,Biology,Music",
        "datasets": [
            {
                "label": "Student 3",
                "data": "120, 90, 45, 90, 14, 100, 88",
                "spanGaps": false
            },
            {
                "label": "Student 2",
                "data": "150, 80, 99, 100, 90, 110, 97",
                "spanGaps": false
            },
            {
                "label": "Student 1",
                "data": "140, 100, 89, 134, 120, 78, 56",
                "spanGaps": false
            }
        ]
    }
    

    in javascript you may handle the response as follows (response contains the above json packet):

    var mydatasets = [];
    var colorslist = ["blue","orange","magenta","green","syrup","navy","bumblebee","turkish","army","ferrari"];
    
    for(var j = 0; j < response.datasets.length; j++) {
      mydatasets.push({label: response.datasets[j].label, boderColor: colorslist[j], data: response.datasets[j].data.splits(','), spanGraphs: true});
    }
    var subjectsData = {
      labels: response.labels.split(','),
      datasets: mydatasets
    }
    
    var options = {
      scales: { 
       yAxes: [{
          ticks: {
                 beginAtZero: true
               },
          scaleLabel: {
                 display: true,
                 labelString: 'Subject Perfomance',
                 fontSize: 14
               }
      }]
     }
    };
    
    var studentsMarksPerformance = new Chart(markschart, {
          type: "line",
          data: subjectsData ,
          options: options
    });
    

    The above is not a complete solution but may help with implementing for..each loop in creating a line chart using Chart.js

提交回复
热议问题