gpt4 book ai didi

javascript - 如何使用来自 mysql 数据库的数据仅在谷歌饼图图例上显示标签和值

转载 作者:行者123 更新时间:2023-11-30 15:40:33 26 4
gpt4 key购买 nike

我正在使用 google charts 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

最佳答案

一旦 '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>

关于javascript - 如何使用来自 mysql 数据库的数据仅在谷歌饼图图例上显示标签和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40902861/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com