converting numbers on y axis to string with K for thousand d3.js

From API Reference, we see d3.formatPrefix

var prefix = d3.formatPrefix(1.21e9);
console.log(prefix.symbol); // "G"
console.log(prefix.scale(1.21e9)); // 1.21

We can use it this way

var yAxis = d3.svg.axis()
    .scale(y)
    .ticks(5)
    .tickFormat(function (d) {
        var prefix = d3.formatPrefix(d);
        return prefix.scale(d) + prefix.symbol;
    })
    .orient("left");

However, in case this is exactly what you mean, we can simplify using d3.format("s")

var yAxis = d3.svg.axis()
    .scale(y)
    .ticks(5)
    .tickFormat(d3.format("s"))
    .orient("left");

This is what i implemented

var yAxis = d3.svg.axis().scale(y).ticks(5).
tickFormat(function (d) {
    var array = ['','k','M','G','T','P'];
    var i=0;
    while (d > 1000)
    {
        i++;
        d = d/1000;
    }

    d = d+' '+array[i];

    return d;}).
orient("left");

it will work for even more than thousand ...


You're looking for tickFormat on the axis object.

var svgContainer = d3.select("body").append("svg")
    .attr("width", 800)
    .attr("height", 100);

//Create the Scale we will use for the Axis
var axisScale = d3.scale.linear()
    .domain([0, 2000])
    .range([0, 600]);

//Create the Axis
var xAxis = d3.svg.axis()
    .scale(axisScale)
    .tickFormat(function (d) {
      if ((d / 1000) >= 1) {
        d = d / 1000 + "K";
      }
      return d;
    });

var xAxisGroup = svgContainer.append("g")
    .call(xAxis);

Check it here: http://jsfiddle.net/3CmV6/2/

This will give you what you want, but I recommend checking the suggestion from robermorales to use d3.format('s') .