谷歌饼图数据表值

时间:2014-04-22 13:39:05

标签: javascript google-visualization

在Google网站上,创建饼图的代码是:

google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Work',     11],
      ['Eat',      2],
      ['Commute',  2],
      ['Watch TV', 2],
      ['Sleep',    7]
    ]);

    var options = {
      title: 'My Daily Activities'
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    chart.draw(data, options);

我有一个全局变量,我想设置它的值并将新值插入到图表中,例如:

    var tmp=MyGlobalVariable+10;
  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Work',     tmp],
      ['Eat',      3],
      ['Commute',  2],
      ['Watch TV', 2],
      ['Sleep',    7]
    ]);

每次我使用tmp var都会消除'工作'从图表。 如何动态设置数据表值?

1 个答案:

答案 0 :(得分:0)

Google图表库从数据集中呈现SVG。

如果你想改变svg,你必须'重绘(drawChart())'图表。

一个小例子(由于时间不长而未经测试,并且可能是错误的):

window.myChart = {
    data : [
        ['Task', 'Hours per Day'],
        ['Work', 11],
        ['Eat', 2],
        ['Commute', 2],
        ['Watch TV', 2],
        ['Sleep', 7]
    ],
    options : {
        title: 'My Daily Activities'
    },
    chart : null,
    init : function(elId) {
        this.chart = new google.visualization.PieChart(document.getElementById(elId));
        this.drawChart();
    },
    drawChart : function()
    {
        this.chart.draw(this.data, this.options);
    }
};

用法:

google.load("visualization", "1", {packages:["corechart"]});
myChart.init('my-chart-id')
google.setOnLoadCallback(myChart.drawChart);

然后每个人都想要更改一些数据:

mychart.data['work'] = 10;
mychart.drawChart();