Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Chart Programmatically with Google Chart Api

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.

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/

like image 867
eiki Avatar asked Nov 12 '13 12:11

eiki


1 Answers

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

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.

like image 141
davidkonrad Avatar answered Oct 25 '22 23:10

davidkonrad