d3.js: tickformat - 如何在不乘以100的情况下添加百分号

36

我的数据中包含百分比,例如:[10.1, 3.2, 5.4]

d3.format("0f")会给我[10, 3, 5]

d3.format("0%")会给我[1010%, 320%, 540%](乘100)

如何获得[10%, 3%, 5%]

我无法确定在第一种情况下何时添加“%”,或者在第二种情况下消除*100。

相关代码:

var formatPercent = d3.format("0f");

var min = 0; 
var max = d3.max(data, function(d) { return + d[5]; });
max = Math.round(max * 1.2); // pad it

//define the x-axis
var xAxis = d3.svg.axis()
                .scale(x)
                .orient('top')
                .ticks(6)
                .tickFormat(formatPercent);

数据看起来是这样的:

{
    "Geography": [
    ["Midwest", 234017797, 498, 8.2, 9.0, 11.3],
    ["Northeast", 265972035, 566, 8.9, 12.1, 13.1],
    ["South", 246235593, 524, 8.1, 8.3, 10.8],
    ["West", 362774577, 772, 9.4,9.9, 11.7]
    ]
}

这些数据中每行的最后三个数字是我用来绘制范围图表的百分比值。我希望根据数据中的高低值,将x轴格式化为整数+%格式。

谢谢!


你能否请发一下你感兴趣的代码的更多部分? - tomtomtom
@tomtomtom 我已经从代码中添加了更多细节。我意识到我可能只需操作最大值和最小值的数据来解决这个问题,但我确实想知道如何简单地添加一个百分号。 - rolfsf
变量formatPercent = function (d) {return d3.format("0f") + "%"}或许可以解决问题,但我不是很确定。 - tomtomtom
1个回答

64

D3 v4更新(使用ES6):

// Can also be axisTop, axisRight, or axisBottom
d3.axisLeft()
    .tickFormat(d => d + "%")

D3 v3的原始回答:

您可以创建自己的格式:

d3.svg.axis()
    .tickFormat(function(d) { return d + "%"; });
如果你想要去掉小数位:
d3.svg.axis()
    .tickFormat(function(d) { return parseInt(d, 10) + "%"; });

需要将值相乘,代码运行正常:.tickFormat(d => (parseInt(d.toString()) * this.resolution).toString()); - asdf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接