Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.js: tickformat - adding a % sign without multiplying by 100

my data has percents as, for example, [10.1, 3.2, 5.4]

d3.format("0f") will give me [10, 3, 5]

d3.format("0%") will give me [1010%, 320%, 540%] (multiplies by 100)

how do I get [10%, 3%, 5%]?

I can't figure out where to add a +"%" to the first case or eliminate the *100 in the second case

the relevant parts of the code:

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); 

and data comes in like this:

{     "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]     ] } 

It's the last three numbers in each line that are the percentage values I'm using to chart ranges. I want the x-axis to be formatted in integer+% format based on the high and low values in the data.

Thank you!

like image 330
rolfsf Avatar asked Aug 27 '13 20:08

rolfsf


1 Answers

Update for D3 v4 (using ES6):

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

Original answer for D3 v3:

You can create your own format:

d3.svg.axis()     .tickFormat(function(d) { return d + "%"; }); 

If you want to get rid of the decimal places:

d3.svg.axis()     .tickFormat(function(d) { return parseInt(d, 10) + "%"; }); 
like image 157
icanc Avatar answered Oct 14 '22 06:10

icanc