【问题标题】:Google Bar chart labeling Dynamic data.How to add labels?谷歌条形图标注动态数据。如何添加标签?
【发布时间】:2014-01-10 14:51:02
【问题描述】:

我正在创建一个 Google 图表条形图!数据来自 MySQL,使用 JSON 和 PHP。 我只想在条形图的末尾添加标签。因为数据是动态的,我觉得很难。

<?php
   $sth = mysql_query("select * from table");
   $rows = array();
   //flag is not needed
   $flag = true;
   $table = array();
   $table['cols'] = array(
                    array('label' => 'Stats', 'type' => 'string'),
                    array('label' => 'Value', 'type' => 'number')
                    );
   $rows = array();
   while($r = mysql_fetch_assoc($sth)) 
   {
    $temp = array();
    $temp[] = array('v' => (string) $r['Stats']); 
    $temp[] = array('v' => (int) $r['Value']); 
    $rows[] = array('c' => $temp);
   }
    $table['rows'] = $rows;
    $jsonTable = json_encode($table);
?>  
<script type="text/javascript">
   google.load('visualization', '1', {'packages':['corechart']});
   google.setOnLoadCallback(drawChart);
   function drawChart() {
      var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
      var options = {
            legend: {position: 'none'},
        bar: {groupWidth: "85%"},
        colors:['#4A9218'],
        hAxis: {
                    viewWindowMode: 'explicit',
                    viewWindow: {
                                 max: 400,
                                 min: 0,
                                 },
                     gridlines: {
                              count: 10,
                                }
                            }          
   };
   var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
   chart.draw(data, options);
 }
</script>
<!--this is the div that will hold the pie chart-->
<div id="chart_div" style="width:100%; height:200px"></div>

结果: 没有标签的条形图 我正在寻找的结果: 条形图,右侧末尾带有标签

【问题讨论】:

    标签: php json google-visualization bar-chart


    【解决方案1】:

    首先,将JSON_NUMERIC_CHECK 添加到您的json_encode 调用中,因为MySQL 将数字作为字符串输出,而将数字作为字符串输入可能会导致某些图表出现问题:

    $jsonTable = json_encode($table, JSON_NUMERIC_CHECK);
    

    如果您想将数据值作为注释添加到条形图上,最简单的方法是创建一个 DataView,其中包含一个计算的 'annotation' 角色列,该列从值列中获取其数据并将其字符串化:

    var view = new google.visualization.DataView(data);
    view.setColumns([0, 1, {
        type: 'string',
        role: 'annotation',
        sourceColumn: 1,
        calc: 'stringify'
    }]);
    

    然后使用视图而不是 DataTable 来绘制图表:

    chart.draw(view, options);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多