如何在D3.js中将Y轴标签保留两位小数并添加百分号?
字母频率分析Web工具Y轴格式化问题解决
问题背景
开发字母频率分析工具,输入句子后统计字母出现次数并以保留两位小数的百分比展示占比,但Y轴标签格式化始终无法达到预期效果。
错误尝试及问题
尝试过以下几种写法,均存在问题:
yAxis.call(d3.axisLeft(y).tickFormat(d3.format(".2f%")()));:输出为千分比量级(如20变成2000%)yAxis.call(d3.axisLeft(y).tickFormat(d3.format(".2f") + "%"));:Y轴完全消失yAxis.call(d3.axisLeft(y).tickFormat(d => d + "%"));:显示百分号但无两位小数
问题根源
你的Y轴数据已经是乘以100后的百分比数值(比如20代表20%),但d3.format(".2f%")会自动将输入值乘以100再添加百分号,导致数值被二次放大;而直接拼接字符串的写法要么语法错误,要么没处理小数位数。
解决方案
只需对已有的百分比数值做小数格式化后拼接百分号,两种可行写法:
写法1:结合d3.format和模板字符串
yAxis.call(d3.axisLeft(y).tickFormat(d => `${d3.format(".2f")(d)}%`));
写法2:使用原生toFixed方法
yAxis.call(d3.axisLeft(y).tickFormat(d => `${d.toFixed(2)}%`));
修改后的核心代码
将displayChart函数中的Y轴调用部分替换为上述任意一种写法即可,修改后的displayChart函数片段:
function displayChart() { svg.selectAll("rect").remove(); var data = alphabet.map(letter => ({letter, frequency: (letterCounts[letter] / totalCount) * 100})); x.domain(data.map(function(d) { return d.letter; })); y.domain([0, 100]); var barGroup = svg.append("g"); // append the rectangles for the bar chart barGroup.selectAll("rect") .data(data) .enter().append("rect") .attr("x", function(d) { return x(d.letter); }) .attr("width", x.bandwidth()) .attr("y", function(d) { return y(d.frequency); }) .attr("height", function(d) { return height - y(d.frequency); }); xAxis.call(d3.axisBottom(x)); // 替换为格式化后的写法 yAxis.call(d3.axisLeft(y).tickFormat(d => `${d3.format(".2f")(d)}%`)); }
内容的提问来源于stack exchange,提问作者Lachlan
相关产品推荐
相关产品推荐

