是的,您可以在同一个图表中同时使用工具提示和注释
为此,您同时使用注释和工具提示列角色
在数据表或数据视图中,在它所代表的每个数据列之后添加角色
数据表
X, Y, annotation role, tooltip role
在以下示例中,使用了数据视图,因此可以动态构建工具提示
为了拥有 html 工具提示,必须做好两件事。
图表选项必须包括...
tooltip: {
isHtml: true
}
并且列角色必须包含一个属性...
p: {html: true}
但是,google图表有一个bug,
使用数据视图时会忽略列属性,
所以我们在绘制时将数据视图转换为数据表...
chart.draw(view.toDataTable(), options); // <-- convert to data table
请参阅以下工作片段...
google.charts.load('current', {
packages:['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
["Element", "Density"],
["Copper", 8.94],
["Silver", 10.49],
["Gold", 19.30],
["Platinum", 21.45]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: 'string',
role: 'annotation',
sourceColumn: 1,
calc: 'stringify'
}, {
type: 'string',
role: 'tooltip',
calc: function (dt, row) {
return '<div class="ggl-tooltip"><div><span>' + dt.getValue(row, 0) + '</span></div><div>' + dt.getColumnLabel(1) + ': <span>' + dt.getValue(row, 1) + '</span></div>';
},
p: {html: true}
}]);
var options = {
annotations: {
textStyle: {
color: 'black',
fontSize: 11,
fontWeight: 'bold',
},
alwaysOutside: true
},
tooltip: {
isHtml: true,
trigger: 'selection'
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart'));
chart.draw(view.toDataTable(), options);
});
.ggl-tooltip {
background-color: #ffffff;
border: 1px solid #e0e0e0;
font-family: Arial, Helvetica;
font-size: 14px;
padding: 8px;
}
.ggl-tooltip div {
margin-top: 6px;
}
.ggl-tooltip span {
font-weight: bold;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>