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
.
The Format Axis dialog box appears. In this go to the Number tab and expand it. Change the Category to Percentage and on doing so the axis data points will now be shown in the form of percentages. By default, the Decimal places will be of 2 digits in the percentage representation.
Display numbers as percentagesOn the Home tab, in the Number group, click the icon next to Number to display the Format Cells dialog box. In the Format Cells dialog box, in the Category list, click Percentage. In the Decimal places box, enter the number of decimal places that you want to display.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With