DamianFox
DamianFox

Reputation: 902

How to parse date on D3 with a specific interval


I'm trying to solve this challenge from FreeCodeCamp. I managed to display the chart with the right data on the Y axis (2000, 4000, 6000, etc...). On the X axis I would like to display just the year with an interval of 5 (1990, 1995, 2000, etc...).

However, what I'm able to display on that axis is something like this: Thu Oct 01 1981 00:00:00 GMT+0100 (CET). Here is the code so far:

var margin = {top: 20, right: 20, bottom: 70, left: 40},
    width = 1200 - margin.left - margin.right,
    height = 700 - margin.top - margin.bottom;

// Parse the date / time
var parseDate = d3.timeParse("%Y-%m-%d");

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

var jsonUrl = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json";

var g = svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.json(jsonUrl, function(error, data) {
  if (error) return console.warn(error);

  var array = data.data;
  var l = array.length;

  var minDate = new Date(array[0][0]);
  var maxDate = new Date(array[l-1][0]);

  var x = d3.scaleBand().rangeRound([0, width]).padding(0.1);

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

  var xAxis = d3.axisBottom()
      .scale(x);

  var yAxis = d3.axisLeft()
      .scale(y).ticks(10);

  array.forEach(function(d) {
        d[0] = parseDate(d[0]);
        d[1] = +d[1];
  });

  x.domain(array.map(function(d) { return new Date(d[0]) }));
  y.domain([0, d3.max(array, function(d) { return d[1]; })]);

  d3.select(".description")
      .append("text")
      .text(data.description);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
    .selectAll("text")
      .style("text-anchor", "end")
      .attr("dx", "-.8em")
      .attr("dy", "-.55em")
      .attr("transform", "rotate(-90)" );

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Value ($)");

  svg.selectAll("bar")
      .data(array)
    .enter().append("rect")
      .style("fill", "steelblue")
      .attr("x", function(d) { return x(d[0]); })
      .attr("width", x.bandwidth())
      .attr("y", function(d) { return y(d[1]); })
      .attr("height", function(d) { return height - y(d[1]); });
});

And, here is the result: enter image description here I'm trying to figure out how to parse the dates, but if a I change the code the values associated with the dates disappear.

What should I do?
Thanks!

UPDATE

I was able to display only the years on the X axis, by simply changing this piece of code:

array.forEach(function(d) {
        d[0] = new Date(d[0]).getFullYear();
        d[1] = +d[1];
  });

Now, I would like to display fewer years by increasing the time interval. I've tried to add ticks like this:

var xAxis = d3.axisBottom()
    .scale(x).ticks(d3.timeInterval(4));

But it doesn't work. How can I fix it?

Upvotes: 1

Views: 426

Answers (1)

pmkro
pmkro

Reputation: 2550

I created a fiddle which I think gives the desired results. The change I did was on your scale band axis creation I updated it to:

var xAxis = d3.axisBottom(x)
    .tickValues(x.domain().filter(function(d, i) {return !(i%4);}));

You can change the i%4 to however many ticks you would like. You could also make it so that it returns only certain data points if you wish eg. return d == Feb 2018 More information found here.

Upvotes: 1

Related Questions