Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove decimal point from my y axis scale in d3js graph

Here is link to my d3js graph http://enjalot.com/inlet/4159384/ Problem is that the y axis which shows Year is having values such as 2008.5 and 2009.0 for json data

 [{count:200,year:2008},
    {count:240,year:2010},
    {count:290,year:2009}];

I want to display Years without any decimal points.How to do it. Here is my d3js code below

    var w = 300,
    h = 300,
    padding = 31,
    p = 10;

var data = [{count:200,year:2008},
    {count:240,year:2010},
    {count:290,year:2009}];

var bar_height = d3.scale.linear()
    .domain(d3.extent(data, function(d) { return d.count; }) )  // min max of count
    .range([p,h-p]);  // min max of area to plot in


var bar_xpos = d3.scale.linear()
    .domain(d3.extent(data, function(d) { return d.year; }) )  // min max of year
    .range([p,w-p]);  // min max of area to plot in


var xAxis = d3.svg.axis()
            .scale(bar_xpos)
            .orient("bottom")
            .ticks(5);  //Set rough # of ticks

var yAxis = d3.svg.axis()
            .scale(bar_height)
            .orient("left")
            .ticks(5);

var svg = d3.select("svg")
    .attr("width", w)
    .attr("height", h);

svg.append("g")
    .attr("class", "axis")
    .attr("transform", "translate(0," + (h - padding) + ")")
    .call(xAxis);

svg.append("g")
    .attr("class", "axis")
    .attr("transform", "translate(" + padding + ",0)")
    .call(yAxis);
like image 596
iJade Avatar asked Nov 28 '12 06:11

iJade


1 Answers

Check out the docs on d3 value formatting.

If you use d3.format() to format your axis, your axis values will look a lot nicer.

var formatxAxis = d3.format('.0f');

var xAxis = d3.svg.axis()
            .scale(bar_xpos)
            .orient("bottom")
            .tickFormat(formatxAxis)
            .ticks(5); 

.0f means:
I want a precision of 0 places after the decimal, and I want values to be fixed, i.e. not rounded but truncated.

You'll notice, however, that since you are fixing the precision to 0 places after the decimal, you will have 2009.5 and 2009.0 both being formatted to 2009. This will mean that two axis ticks could have the same value. This error will go away once you have enough data points over more years.

like image 125
rosshamish Avatar answered Sep 27 '22 23:09

rosshamish