将值数组添加到我的图表

时间:2016-02-10 23:20:53

标签: javascript charts

我想从给定的值数组中向我的图表中添加值(" my_values")。

window.onload = f;

function f() {
    var my_values = [5, 8, 22, 6, 11];

    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);
        function drawChart() {
        var data = google.visualization.arrayToDataTable([
            ['Number', 'Value'],
            [1, 12],
            [2, 12]
            /*
            I need to add an array "my_values" in a way presented below.
            [3, 5],
            [4, 8],
            [5, 22],
            [6, 6],
            [7, 11]
            */
        ]);

        var options = {
            title: 'Title',
            hAxis: {title: 'X', minValue: 0, maxValue: 100},
            vAxis: {title: 'Y', minValue: 0, maxValue: 2400},
            fontSize: '18',
            legend: 'none',
            pointSize: 2.5
        };

        var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));

        chart.draw(data, options);

    }

}

我的问题是这些值应该是数组([index,value])。如果我创建一个数组数组,那么我的代码无法正常工作。

2 个答案:

答案 0 :(得分:0)

尝试类似的事情:

window.onload = f;

function f() {
    var chartData = [['Number', 'Value'],[1, 12],[2, 12]];
    var my_values = [5, 8, 22, 6, 11];
    var index = chartData.length;

    for(var i = 0; i < my_values.length; i++){
        chartData.push([index++, my_values[i]]);
    }

    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);
        function drawChart() {
        var data = google.visualization.arrayToDataTable(chartData);

        var options = {
            title: 'Title',
            hAxis: {title: 'X', minValue: 0, maxValue: 100},
            vAxis: {title: 'Y', minValue: 0, maxValue: 2400},
            fontSize: '18',
            legend: 'none',
            pointSize: 2.5
        };

        var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));

        chart.draw(data, options);

    }

答案 1 :(得分:0)

我相信你可以做到

    var counter = original.length
    var addThese = []

    for(var i = 0; i < my_values.length; i++){
        addThese.push([counter+1,my_values[i]])
        counter++
    } 
    original = original.concat(addThese)