John Power
John Power

Reputation: 105

Correctly format year on x axis d3

I am working with a scatterplot in d3. The x axis represents the YEAR. I get information from the database and plot it as circles on the graph. My problem is how do I parse the x value so it is formatted as a year? ie. currently it displays like 1,999 but it should look like 1999. Can someone show me how I should parse this correctly to get the right format! Here is the relevant code:

var margin = {top: 20, right: 20, bottom: 30, left: 60},
    width = 1800 - margin.left - margin.right,
    height = 600- margin.top - margin.bottom;

var YearFn = function(d) {return d.YEAR ;};

var Num_citationsFn = function(d) {return d.counter;};

var x = d3.scale.linear()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis().scale(x).orient("bottom");    

var yAxis = d3.svg.axis().scale(y).orient("left");

d3.json("connection4.php", function(error,data) {

dataJson.forEach(function(d) {
    d.YEAR = +d.YEAR;  
    d.counter = d.counter;

x.domain([d3.min(data, YearFn)-1, d3.max(data, YearFn)+1]);
y.domain([d3.min(data, Num_citationsFn)-1, d3.max(data, Num_citationsFn)+1]);

var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)
  .append("text")
  .attr("class", "label")
  .attr("x", width)
  .attr("y", -6)
  .style("text-anchor", "end")
  .text("YEAR");

  // y-axis
svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
  .append("text")
  .attr("class", "label")
  .attr("transform", "rotate(-90)")
  .attr("y", 6)
  .attr("dy", ".71em")
  .style("text-anchor", "end")
  .text("Number of citations");

var circles = svg.selectAll("circle")
        .data(data)
        .enter()
        .append("circle")
        .attr("class", "dot")
        .attr("r", 8.5)
        .attr("cx", function(d) {return x(YearFn(d))})
        .attr("cy", function(d) {return y(Num_citationsFn(d))})
        .style("fill","blue")

});

I appreciate any feedback I am new to d3! Thanks in advance!

Upvotes: 0

Views: 788

Answers (1)

meetamit
meetamit

Reputation: 25157

xAxis.tickFormat(d3.format('0f'));

Upvotes: 1

Related Questions