1
votes

Having a brutal time trying to illustrate a historic S&P 500 performance chart year-by-eyar. No matter what I try, the X-axis "ticks()" method is ignored and simply uses a value of 1. Which is very hard to see.

var margin = {top: 20, right: 20, bottom: 70, left: 40},
    width = $('#sp501').width() - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

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

var x = d3.scaleBand().range([0, width], .05);

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

var xAxis = d3.axisBottom(x)
        .tickFormat(d3.timeFormat("%Y"))
        .ticks(10); // I can't figure out why this is ignored!

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

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

d3.csv("data/sp500-historical.csv", function(error, data) {

    data.forEach(function(d) {
        d.date = parseDate(d.date);
        d.value = +d.value;
    });

    x.domain(data.map(function(d) { return d.date; }));
    y.domain([-60, 60]);

  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)" );

The data is in a convention format:

date,value
1928-01,43.81
1929-01,-8.30
1930-01,-25.12
1931-01,-43.84
1932-01,-8.64
1933-01,49.98
1934-01,-1.19
1935-01,46.74
1936-01,31.94

And I've tried converting the dates to just integer years to see if that works, to no avail.

Am I nuts or is something wrong with X-axis ticks using dates?

Thanks!

1
I'm having the same issue here. Is with numbers for me though, isn't just with datesalexrogers

1 Answers

0
votes

While not setting the ticks explicitly, this snippet worked to feed the extent to d3 before the axisBottom call, which then cleaned up the display.

svg.append("g")
  .attr("class", "e4rAxis")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x));