i am using d3.js charts to plot y axis and x axis. It's working fine, but the values in y axis you can say range is say 0 to 10000 and I want if the number is greater than thousand it will come with K.
if the number is 1000 it will show 1K, for 15000 it will show on y axis ticks 15K.
How to do that? I am not able to manupulate y.domain
and range functions for the string values.
var y = d3.scale.linear().range([ height, 0 ]);
y.domain([
0,
d3.max(cities, function(c) { return d3.max(c.values, function(v) { return v.count; }); })
]);
If you wish to edit the labels on the ticks you can use the tickFormat function.
For example, your y axis function would look something like this:
Then you just have to call it. Assuming you have a variable called svg that references your svg chart:
To make things a little clearer I've created this jsfiddle based on this tutorial, adapted to display axis tick labels in the way you describe above if the value is greater than or equal to 1000. If you run it a few times you will see how different axis values are handled.
From API Reference, we see
d3.formatPrefix
We can use it this way
However, in case this is exactly what you mean, we can simplify using
d3.format("s")
You're looking for
tickFormat
on the axis object.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')
.Try this
This is what i implemented
it will work for even more than thousand ...
A concise approach:
This returns
1K
for1000
, 1M for1,000,000
, and so on.Note: Beyond quadrillion, you may wanna go through Number.MAX_SAFE_INTEGER.