Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display y-axis as percentages?

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.

like image 790
grautur Avatar asked Apr 18 '12 02:04

grautur


People also ask

How do you show Y-axis as a percentage?

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.

How do you change a chart to a percentage?

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.


1 Answers

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:

  • http://bl.ocks.org/1166403

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.

like image 90
mbostock Avatar answered Oct 19 '22 19:10

mbostock