javascript 使用 Google Chart Api 以编程方式更新图表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19928794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:16:39  来源:igfitidea点击:

Update Chart Programmatically with Google Chart Api

javascriptjquerygoogle-visualization

提问by eiki

I want to add/remove some data to my multiple charts. But I declare dataTable var globally and set it onCallBack, no problem. But I want to add/remove data after callback with Ajax.

我想在我的多个图表中添加/删除一些数据。但是我全局声明了dataTable var并将其设置为onCallBack,没问题。但是我想在使用 Ajax 回调后添加/删除数据。

var testRows = [
    ['Test-A', 4, 3],
    ['Test-B', 1, 2],
    ['Test-C', 3, 4],
    ['Test-D', 2, 0],
    ['Test-E', 2, 5]
];
var testRow = ['Test-F', 8, 1];
var data = null;

google.load("visualization", "1", {
    packages: ["corechart", 'table']
});

google.setOnLoadCallback(function () {
    data = new google.visualization.DataTable();
    data.addColumn('string', 'Task');
    data.addColumn('number', 'Hours per Day');
    data.addColumn('number', 'How Sexy');
    data.addRows(testRows);
    drawChart('tablechart', 'div_id_1', testRow, null);
    drawChart('columnChart', 'div_id_2', null, null);
});

function drawChart(chartType, containerID, row, options) {
    data.addRow(row);
    var containerDiv = document.getElementById(containerID);
    var chart = false;
    if (chartType.toUpperCase() == 'BARCHART') {
        chart = new google.visualization.BarChart(containerDiv);
    } else if (chartType.toUpperCase() == 'COLUMNCHART') {
        chart = new google.visualization.ColumnChart(containerDiv);
    } else if (chartType.toUpperCase() == 'PIECHART') {
        chart = new google.visualization.PieChart(containerDiv);
    } else if (chartType.toUpperCase() == 'TABLECHART') {
        chart = new google.visualization.Table(containerDiv);
    }

    if (chart == false) {
        return false;
    }
    chart.draw(data, options);
}

drawChart('tablechart', 'div_id_1', ['abiz',5,2], null);
drawChart('columnChart', 'div_id_2', ['cabiz',5,2], null);

http://jsfiddle.net/eron/gD7KL/1/

http://jsfiddle.net/eron/gD7KL/1/

回答by davidkonrad

You simply manipulate your DataTableand then call draw()for each of your tables. Like this :

您只需操作您的DataTable然后调用draw()您的每个表。像这样 :

var columnChart, tableChart;
document.getElementById('change-btn').onclick=function() {
    data.removeRow(0);
    data.insertRows(0, [['Test-A-changed', 14, 13]]);
    columnChart.draw(data);
    tableChart.draw(data);
}

the fiddle above forked to demonstrate this -> http://jsfiddle.net/Hw9U5/I changed the drawChart-function as well to keep track of the chart instances.

上面的小提琴分叉来证明这一点 - > http://jsfiddle.net/Hw9U5/我也改变了drawChart-function 以跟踪图表实例。