我正在使用Google可视化图表(甜甜圈图表)
图表具有工具提示
单击按钮,我们可以动态显示工具提示吗?
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task');
data.addColumn('number', 'Hours per Day');
data.addRows([
['A', roundNumber(11 * Math.random(), 2)],
['B', roundNumber(2 * Math.random(), 2)],
['C', roundNumber(2 * Math.random(), 2)],
['D', roundNumber(2 * Math.random(), 2)],
['E', roundNumber(7 * Math.random(), 2)]
]);
var options = {
width: 450,
height: 300,
colors: ['#ECD078','#ccc','#C02942','#542437','#53777A'],
legend: {position:'none'},
pieHole: 0.4,
animation: {duration:800,easing:'in'}
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
function roundNumber(num, dec) {
var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
return result;
}
$(document).ready(function(){
$("#button").click(function(){
alert('show tool tips')
});
});
答案 0 :(得分:1)
首先,需要使用最新版本的Google图表,
jsapi
加载程序已过时,不应再使用。
改为使用-> <script src='https://www.gstatic.com/charts/loader.js'></script>
这只会更改load
语句。
有关更多信息,请参见以下片段和update library loader code。
接下来,我们可以使用以下选项允许在选择切片时显示工具提示...
tooltip: {
trigger: 'both'
}
我们可以使用以下选项选择多个切片...
selectionMode: 'multiple',
然后,当我们单击按钮时,我们选择切片,其中显示了工具提示。
google.charts.load('current', {
packages:['corechart']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task');
data.addColumn('number', 'Hours per Day');
data.addRows([
['A', roundNumber(11 * Math.random(), 2)],
['B', roundNumber(2 * Math.random(), 2)],
['C', roundNumber(2 * Math.random(), 2)],
['D', roundNumber(2 * Math.random(), 2)],
['E', roundNumber(7 * Math.random(), 2)]
]);
var options = {
width: 450,
height: 300,
colors: ['#ECD078','#ccc','#C02942','#542437','#53777A'],
legend: {position:'none'},
pieHole: 0.4,
animation: {duration:800,easing:'in'},
selectionMode: 'multiple',
tooltip: {
trigger: 'both'
}
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
$("#button").click(function(){
var selection = [];
$.each(new Array(data.getNumberOfRows()), function (rowIndex) {
if (data.getValue(rowIndex, 1) > 0) {
selection.push({row: rowIndex});
}
});
chart.setSelection(selection);
});
});
chart.draw(data, options);
});
function roundNumber(num, dec) {
var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
return result;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='https://www.gstatic.com/charts/loader.js'></script>
<div id="button" data-role="button">Show Tool Tips</div>
<div id='chart_div'></div>
注意:您还应该等待图表的'ready'
事件,
在分配按钮单击事件之前。
否则,将引发错误。