简体   繁体   English

将数据从json推送到Chart.js标签和数据

[英]Pushing data from json to Chart.js labels and data

I am using the Chart.js lib to make charts. 我正在使用Chart.js库制作图表。

I have a json array that I am getting from a database. 我有一个从数据库获取的json数组。

Here is the console log of it: Data 这是它的控制台日志: 数据

I need to get the address, speed, and speed limit for every element in the list and use it in a chart. 我需要获取列表中每个元素的地址,速度和速度限制,并在图表中使用它。

My current code is as follows: 我当前的代码如下:

function ShowChart() {
   var popCanvas = document.getElementById("speedLimitsChart");
   console.dir(speeddata);

   var labels = speeddata.map(function (e) {
       return e.Adress;
   });
   var speed = speeddata.map(function (e) {
       return e.Speed;
   });

   var speedlimits = speeddata.map(function (e) {
       return e.SpeedLimits;
   });

   console.dir(labels);
    var barChart = new Chart(popCanvas, {
        type: 'bar',

        data: {
            datasets: [{
                label: 'Speed',
                data: speed,
                backgroundColor: '#1E90FF'
            }, {
                label: 'Speed Limits',
                data: speedlimits,
                backgroundColor: '#B22222',
                type: 'line'
            }],

        },
        labels: labels 
    });
}

But in the result I only have the first element in my chart, and there are no labels. 但是结果是我的图表中只有第一个元素,并且没有标签。

Here is the output screen: Chart 这是输出屏幕: 图表

I checked speed , speedlimits and labels and all of them have 2 elements. 我检查了speedspeedlimitslabels ,它们都有2个元素。 Can you please advise where my problem might be? 您能告诉我我的问题可能在哪里吗?

I found where is my problem 我发现我的问题在哪里

I need to write labels inside of data 我需要在数据内写标签

Like this 像这样

var barChart = new Chart(popCanvas, {
    type: 'bar',

    data: {
        labels: labels ,
        datasets: [{
            label: 'Speed',
            data: speed,
            backgroundColor: '#1E90FF'
        }, {
            label: 'Speed Limits',
            data: speedlimits,
            backgroundColor: '#B22222',
            type: 'line'
        }],

    },

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM