using array values in chart.js data and label field

最后都变了- 提交于 2019-12-12 07:16:04

问题


I wish to pass values of an array to the data and label fields of the chart.js dataset.

Here the code from success of ajax call made to fetch json data. I fetch the json data and store it into an array.

Data = jQuery.parseJSON(result);
var count = Data.length;
var counter = 0;
while(count > 0) {
    LabelResult[counter] =[Data[counter].TIME];
    counter++;
    count --;
}

Now i wish to use this label values into the labels filed.

var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: [LabelResult],
        datasets: [{
            label: '# of Votes',
            data: [DataResult],
            borderWidth: 1
        }]
    }    
});

But there seems some issue and the data is not getting rendered on the chart


回答1:


LabelResult is an array, change

labels: [LabelResult]

to

labels: LabelResult

Also:

data: [DataResult]

to

data: DataResult

Like:

var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: LabelResult,
        datasets: [{
            label: '# of Votes',
            data: DataResult,
            borderWidth: 1
        }]
    }    
});



回答2:


I think you could try to remove some brackets.

while(count > 0){
     LabelResult[counter] = Data[counter].TIME; // here removed brackets
      counter++;
      count --;
}    

and

data: {
    labels: LabelResult, // here removed brackets
    datasets: [{
        label: '# of Votes',
        data: DataResult, // here removed brackets
        borderWidth: 1
    }]
},  

I hope that will works.



来源:https://stackoverflow.com/questions/38869815/using-array-values-in-chart-js-data-and-label-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!