2012-06-07 38 views

回答

13

我所做的是用1列和1个数据点(设置为0)初始化我的图表。然后,每当数据被添加,我检查是否只有1列,它是虚拟列,然后我删除它。我也隐藏了图例,以便它不会出现在虚拟列中,然后在新列添加时添加它。

下面是一些示例代码,你可以插入Google Visualization Playground,这就是我所说的。你应该看到空的图表2秒钟,然后数据将被添加,列将出现。

var data, options, chart; 

function drawVisualization() { 

    data = google.visualization.arrayToDataTable([ 
    ['Time', 'dummy'], 
    ['', 0], 
    ]); 

    options = { 
    title:"My Chart", 
    width:600, height:400, 
    hAxis: {title: "Time"}, 
    legend : {position: 'none'} 
    }; 

    // Create and draw the visualization. 
    chart = new google.visualization.ColumnChart(document.getElementById('visualization')); 
    chart.draw(data,options); 
    setTimeout('addData("12:00",10)',2000); 
    setTimeout('addData("12:10",20)',3000); 
} 

function addData(x,y) { 
    if(data.getColumnLabel(1) == 'dummy') { 
    data.addColumn('number', 'Your Values', 'col_id'); 
    data.removeColumn(1); 
    options.legend = {position: 'right'}; 
    } 

    data.addRow([x,y]); 
    chart.draw(data,options); 
}​ 
9

对这个问题更好的解决方案可能是使用注释列而不是数据列,如下所示。使用此解决方案,您无需使用任何setTimeout或自定义功能来删除或隐藏列。试试把下面的代码粘贴到Google Code Playground

function drawVisualization() { 
    var data = google.visualization.arrayToDataTable([ 
     ['', { role: 'annotation' }], 
     ['', ''] 
    ]); 

    var ac = new google.visualization.ColumnChart(document.getElementById('visualization')); 
    ac.draw(data, { 
     title : 'Just a title...', 
     width: 600, 
     height: 400 
    }); 
} 

0

的方式我这样做是通过禁用扇形,在假装值关闭提示,填料,使其灰色。我相信有更聪明的方法可以做到这一点,但这对其他方法没有的地方适用。

唯一的缺点是它将图例中的两个项都设置为灰色。我想你或许可以只添加第三个项目,并使其仅在图例上不可见。尽管我喜欢这种方式。

function drawChart() { 
// Define the chart to be drawn. 
    data = new google.visualization.DataTable(); 
    data.addColumn({type: 'string', label: 'Result'}); 
    data.addColumn({type: 'number', label: 'Count'}); 
    data.addRows([ 
      ['Value A', 0], 
      ['Value B', 0] 
    ]); 

    var opt_pieslicetext = null; 
    var opt_tooltip_trigger = null; 
    var opt_color = null; 
    if (data.getValue(1,1) == 0 && data.getValue(0,1) == 0) { 
    opt_pieslicetext='none'; 
    opt_tooltip_trigger='none' 
    data.setCell(1,1,.1); 
    opt_color= ['#D3D3D3']; 
    } 
    chart = new google.visualization.PieChart(document.getElementById('mydiv')); 
    chart.draw(data, {sliceVisibilityThreshold:0, pieSliceText: opt_pieslicetext, tooltip: { trigger: opt_tooltip_trigger }, colors: opt_color }); 
}