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 轴格式化为整数+% 格式。

谢谢!

4

1 回答 1

63

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) + "%"; });
于 2013-08-27T22:31:59.980 回答