如何为行添加数据列智能动态?

时间:2014-04-22 07:04:53

标签: javascript google-visualization

这个问题与google折线图有关,它会显示不同的线条,即循环线条

我有一个数据数组,长度是未知的,即Cycle_x。

我将动态获取数据

arrayCycleName=['Cycle_1','Cycle_3','Cycle_3','Cycle_4',....];

arrayModNames=['mod_1','mod_2','mod_3','mod_4'];

arrayCycle_1_Data=[50,30,10,15];
arrayCycle_2_Data=[40,20,42,44];
arrayCycle_3_Data=[30,34,36,40];
so on..

我正在使用DataTale

var data = new google.visualization.DataTable();
var chart = new google.visualization.LineChart(document
            .getElementById('charts'));

data.addColumn('string', 'Module Names');

for (i=0;i<arrayCycleName.lenght;i++)
data.addColumn('number', arrayCycleName[i]);

现在的问题是如何使用任何循环获取如下数据。

data=[
       ['CycleName', 'Cycle_1', 'Cycle_2', 'Cycle_3'],
       ['Mod_1'    ,    50    ,    40    ,      30  ],
       ['Mod_2'    ,    30    ,    20    ,      34  ],
       ['Mod_3'    ,    10    ,    42    ,      36  ],
       ['Mod_4'    ,    15    ,    44    ,      40  ]
     ]

所以我可以打电话

chart.draw(data,{title: 'charts'});

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案:

function drawChart() {

    var data = new google.visualization.DataTable();

    var arrayCycleName = ['Cycle_1', 'Cycle_3', 'Cycle_3'];

    var arrayModNames = ['mod_1', 'mod_2', 'mod_3', 'mod_4'];

    var arrayCycle_1_Data = [50,30,10,15];
    var arrayCycle_2_Data = [40,20,42,44];
    var arrayCycle_3_Data = [30,34,36,40];

    var arrayCycles = [arrayCycle_1_Data, arrayCycle_2_Data, arrayCycle_3_Data]

    data.addColumn('string', 'CycleName');
    for (var i = 0; i < arrayCycleName.length; ++i) {
        data.addColumn('number', arrayCycleName[i]);
    }

    for (var i = 0; i < arrayModNames.length; ++i) {
        var row = [];
        row.push(arrayModNames[i]);
        for (var j = 0; j < arrayCycles.length; ++j) {
            row.push(arrayCycles[j][i]);
        }
        console.log(row);
        data.addRow(row);
    }
    console.log(data);

    var options = {
        title: 'charts',
        vAxis: {
            minValue: 0
        }
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
}

请参阅example at jsbin