我正在使用d3来创建图表 - (仍在学习这两个图表)。我希望我的Y轴以百分比显示值。 Y轴上的最小值和最大值是动态分配的,因此轴刻度有时可以是25% to 38%
,有时甚至是13% to 16%
。
如果有25% to 28%
这样的范围相对较大,我可以正常显示数字,即25%, 28%, 31% ....
然而,对于一个非常小的范围,我注意到它显示为13%, 14%, 14%, 15%, 15%,...
(数字重复,可能是因为幕后可能会说,14.2%
和14.8%
。
在这种情况下,我希望数字显示为指定1位小数,例如13.5%
。
我知道我可以指定
.tickFormat(d3.format(".1%"))
这给了我在这种情况下我需要的东西。问题是当我有一个更大的规模时,它基本上给了我25.0%, 28.0%, 31.0%,...
,在这种情况下,我不喜欢小数精度。
我能用一种简单的方法处理每种情况吗?任何指导都将非常感激。
答案 0 :(得分:1)
正如评论中所提到的,你可以检查范围是否足够大,并根据它添加小数点格式,但这不会很干净。我建议您将自己的函数作为tickFormat
传递,该函数应用格式,具体取决于值是否包含小数部分。类似的东西:
// defined your formatters somewhere above
var decimalFormatter = d3.format(".1");
myAxis.tickFormat(function(d) {
if (!Number.isInteger(d)) {
d = decimalFormatter(d); // add the decimal point for non-integers
}
return d + '%';
}
示例代码:
// defined your formatters somewhere above
var decimalFormatter = d3.format(".1");
var tickFormat = function(d) {
if (!Number.isInteger(d)) {
d = decimalFormatter(d); // add the decimal point for non-integers
}
return d + '%';
};
console.log(tickFormat(12.5)); // 12.5%
console.log(tickFormat(14)); // 14%
console.log(tickFormat(15)); // 15%

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;
您可以根据需要以任何特定方式调整上述功能。例如,如果您使用字符串而不是数字,则需要先转换为数字,然后使用Number.isInteger
,因为它总是会返回false
作为字符串。
答案 1 :(得分:0)
您已经有了小规模数字的解决方案:d3.format(.1%)
。对于大规模的数字,您可以使用 d3.format(~%)
。这将自动删除尾随零,例如,25.0%, 28.0%, 31.0%,...
d3-format 的 documentation 提到:
<块引用>~
选项会修剪所有格式类型中无关紧要的尾随零。这最常与 r
、e
、s
和 %
类型结合使用。