如何使用来自 mysql db 的数据仅在 google 饼图图例上显示标签和值

how to display label and values only on google pie chart legend with data from mysql db

我正在使用 google 图表 API 来显示饼图,我希望图例仅显示标签和值,但我被卡住了,我搜索的大部分答案都包含百分比。我该怎么做?

我的代码如下:

PHP

$table         = array();
$table['cols'] = array(
    //Labels for the chart, these represent the column titles
    array('id' => '', 'label' => 'Country', 'type' => 'string'),
    array('id' => '', 'label' => 'Number of Devices', 'type' => 'number')
); 

$rows = array();
foreach($exec as $row){
    $temp = array();

    //Values
    $temp[] = array('v' => (string) $row['Country']);
    $temp[] = array('v' => (int) $row['Number of Devices']); 
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows; 
$jsonTable = json_encode($table);
echo $jsonTable

JavaScript

google.charts.load('current', {'packages':['corechart']});

google.charts.setOnLoadCallback(drawChart);

function drawChart() {

  var PieChart_options = {
      title: 'Number of Devices per country',
      pieSliceText: 'value',
      width: 900, 
      height: 500
    };

 var data = new google.visualization.DataTable(<?=$jsonTable?>);

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

}

我想这样创建: pie chart with label and value on legend

简单,把mysql的数据格式化成this

 ['Work (11)',     11]

它不会影响你的图表。

可以修改图表,一旦 'ready' 事件触发

一定要设置好事件监听器,绘制图表前

图例标签的显示顺序应与提供的数据相同

以下代码片段通过检查属性值找到图例标签

然后从数据中添加值...

google.charts.load('current', {
  callback: function () {
    var data = new google.visualization.DataTable({
      "cols": [
        {"label": "Country", "type": "string"},
        {"label": "# of Devices", "type": "number"}
      ],
      "rows": [
        {"c": [{"v": "Canada"}, {"v": 33}]},
        {"c": [{"v": "Mexico"}, {"v": 33}]},
        {"c": [{"v": "USA"}, {"v": 34}]}
      ]
    });

    var container = document.getElementById('chart_div');
    var chart = new google.visualization.PieChart(container);

    google.visualization.events.addListener(chart, 'ready', function () {
      var rowIndex = 0;
      Array.prototype.forEach.call(container.getElementsByTagName('text'), function(label) {
        // find legend labels
        if ((label.getAttribute('text-anchor') === 'start') && (label.getAttribute('fill') !== '#ffffff')) {
          label.innerHTML += ' (' + data.getValue(rowIndex++, 1) + ')';
        }
      });
    });

    chart.draw(data, {
      height: 400,
      width: 600
    });
  },
  packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>