Google Chart柱状图千位分隔符及数值单位后缀设置问题
Google Chart堆叠柱状图数值格式调整方案
核心调整点
- 移除
NumberFormat中冲突的pattern配置,原有groupingSymbol、suffix、fractionDigits已经可以满足「空格千分位+单位后缀+无小数」的格式要求,多余的pattern会覆盖千位分隔规则 - 给所有数值列(列索引1、3、5)都执行格式化操作,原代码仅格式化了第5列,导致另外两个系列的数值格式不生效
- 在
options中新增vAxis.format配置,让Y轴侧边的数值也应用统一格式 - 调整annotation列的计算逻辑,返回格式化后的数值文本,确保柱内标注格式符合要求
修改后完整代码
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <div class="Container50" id="piechart" style="width: 800px; height: 500px;"></div> <script type="text/javascript"> google.charts.load('current', {'packages': ['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Genre', 'Vk', {role: 'annotation'}, 'Sta', {role: 'annotation'}, 'Va', { role: 'annotation' } ], ['Ps', 360000, 'Vk', 82000, 'Sta', 200000, 'Vy'], ['Ds', 360000, 'Vk', 82000, 'Sta', 200000, 'Vy'] ]); // 初始化格式化器,移除冲突的pattern配置 var formatter = new google.visualization.NumberFormat({ groupingSymbol: ' ', suffix: ' Kč', fractionDigits: 0 }); // 给所有数值列执行格式化 [1,3,5].forEach(colIndex => formatter.format(data, colIndex)); var view = new google.visualization.DataView(data); view.setColumns([0, 1, { calc: function (dt, row) { // 返回格式化后的数值作为标注 return dt.getFormattedValue(row, 1); }, type: "string", role: "annotation", }, 3, { calc: function (dt, row) { return dt.getFormattedValue(row, 3); }, type: "string", role: "annotation" }, 5, { calc: function (dt, row) { return dt.getFormattedValue(row, 5); }, type: "string", role: "annotation" }, ]); var options = { title: '', isStacked: true, legend: { position: 'right'}, chartArea: { left: "10%", top: "4%", height: "92%", width: "70%" }, colors: ['#3366CC','#DC3912','#23C228', '#000000'], // 配置Y轴数值格式,和自定义格式化器规则对齐 vAxis: { format: '#,##0 Kč' } }; var chart = new google.visualization.ColumnChart(document.getElementById('piechart')); chart.draw(view, options); // 原有的图表URI导出逻辑按需保留 if(document.getElementById("j_idt26:chart")) { document.getElementById("j_idt26:chart").value = chart.getImageURI(); } } </script>
内容的提问来源于stack exchange,提问作者Martin Hofman
相关产品推荐
相关产品推荐

