Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
196
rated 0 times [  200] [ 4]  / answers: 1 / hits: 23459  / 12 Years ago, wed, april 18, 2012, 12:00:00

I'm making a chart, and I want my y-axis tick labels to display as percentages (instead of decimals). How can I do this?



My current code looks something like



yAxis
.append(text)
.attr(class, ticklabel)
.attr(x, 0)
.attr(y, y)
.attr(dy, .5em)
.attr(text-anchor, middle)
.text(y.tickFormat(5))
.attr(font-size, 10px)


I noticed that d3 has a format specifier, but I'm not sure how to use these in conjunction with tickFormat.


More From » svg

 Answers
2

It looks like you authoring the axis by hand. I recommend using the d3.svg.axis component instead, which does the rendering for you. For example:





If you want to format ticks as percentages, then use d3.format's % directive:



var formatPercent = d3.format(.0%);

var yAxis = d3.svg.axis()
.scale(y)
.orient(left)
.tickFormat(formatPercent);


You can instead use the p directive if you want to round to the percentage to significant digits.



To answer your question more directly, you use d3.format instead of the scale's tickFormat. Scales provide a default tickFormat for convenience, but if you want different behavior, then you use a custom d3.format rather than the scale's default one.


[#86176] Monday, April 16, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isaacvalentinn

Total Points: 325
Total Questions: 120
Total Answers: 131

Location: North Korea
Member since Tue, Jun 16, 2020
4 Years ago
isaacvalentinn questions
Mon, Jan 18, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Wed, Sep 23, 20, 00:00, 4 Years ago
;