d3.js:tickformat - 添加%符号而不乘以100

时间:2013-08-27 20:16:47

标签: formatting d3.js

我的数据的百分比为,例如[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轴格式化为整数+%格式。

谢谢!

1 个答案:

答案 0 :(得分:47)

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) + "%"; });