我正面临Google图表的问题。我想要一个饼图,显示带有标记图例的所有值,包括低于0.1%的非常小的值。
说我有以下数据:
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 66],
['Sleep', 33.95],
['Eat', 0.05]
]);
(总计匹配最多100个)
现在的问题是,在计算百分比时,Google Charts会将这些值四舍五入,导致33.95变为34,因此0.05变为0。
此处示例:https://jsfiddle.net/4qe7h21s/
有没有办法让图表引擎创建2位小数而不是1位小数的百分比?
答案 0 :(得分:2)
因为没有选项来更改百分比的格式或精度
首先,需要设置sliceVisibilityThreshold: 0.0001
因此'Eat'
不属于'Other'
接下来,在数据中提供自定义格式化值
{v: 66, f: '66.00%'}
将pieSliceText
和tooltip.text
设置为'value'
由于'Eat'
的切片太小,请使用
tooltip.trigger: 'selection'
参见以下示例,切片显示正确的百分比
点击'Eat'
的图例项以查看工具提示
google.charts.load('current', {
callback: function () {
new google.visualization.PieChart(document.getElementById('chart_div')).draw(
google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', {v: 66, f: '66.00%'}],
['Sleep', {v: 33.95, f: '33.95%'}],
['Eat', {v: 0.05, f: '0.05%'}]
]),
{
height: 400,
legend: {
position: 'right'
},
pieSliceText: 'value',
sliceVisibilityThreshold: 0.0001,
title: 'My Daily Activities',
tooltip: {
showColorCode: true,
text: 'value',
trigger: 'selection'
},
width: 600
}
);
},
packages: ['corechart', 'table']
});

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
&#13;
答案 1 :(得分:0)
我还需要在悬停时显示工具提示,但不仅仅是点击,所以我找到了解决方案,使用处理事件API:https://developers.google.com/chart/interactive/docs/events。这是一个小改进,适用于切片和图例悬停:
function mouseOverHandler(selection) {
chart.setSelection([selection]);
}
function mouseOutHandler() {
chart.setSelection();
}
google.visualization.events
.addListener(chart, 'onmouseover', mouseOverHandler);
google.visualization.events
.addListener(chart, 'onmouseout', mouseOutHandler);
这是一个完整的工作示例(基于@ WhiteHat的代码段):
google.charts.load('current', {
callback: function () {
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(
google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', {v: 66, f: '66.00%'}],
['Sleep', {v: 33.95, f: '33.95%'}],
['Eat', {v: 0.05, f: '0.05%'}]
]),
{
height: 400,
legend: {
position: 'right'
},
pieSliceText: 'value',
sliceVisibilityThreshold: 0.0001,
title: 'My Daily Activities',
tooltip: {
showColorCode: true,
text: 'value',
trigger: 'selection'
},
width: 600
}
);
function mouseOverHandler(selection) {
chart.setSelection([selection]);
}
function mouseOutHandler() {
chart.setSelection();
}
google.visualization.events
.addListener(chart, 'onmouseover', mouseOverHandler);
google.visualization.events
.addListener(chart, 'onmouseout', mouseOutHandler);
},
packages: ['corechart', 'table']
});
#chart_div svg g:last-child > g:last-child {
pointer-events: none;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>