whileone
whileone

Reputation: 2805

Format ticks in D3

I'm plotting the graphs with "number of clicks" as Y axis and "date" as X axis. Because of the large amount of data, the X axis is jumbled and couldn't display all the dates. I tried to use ticks(d3.time.months, 1) and tickFormat('%b %Y') to cur off some of the ticks. When I run the code, I got "getMonth() is not defined" for my data.

.tsv file:

date count
2013-01-01 4
2013-03-02 5

sample code:

var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .1, 0);

var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")            
        .ticks(d3.time.months, 1)
        .tickFormat(d3.time.format('%b %Y'))

d3.tsv("data_Bar_Chart_Paino_Kristen.tsv", type, function(error, data) {
      x.domain(data.map(function(d) { return d.date; }));
      y.domain([0, d3.max(data, function(d) { return d.hits; })]);


      var temp = height + 30; //+15

        svg.append("g")
          .attr("class", "x axis")
          .attr("transform", "translate(-8," + temp + ")")
          .call(xAxis);
       svg.selectAll(".bar")
          .data(data)
          .enter().append("rect")
          .attr("class", "bar")
          .attr("x", function(d) { return x(d.date); })
          .attr("width", x.rangeBand())
          .attr("y", function(d) { return y(d.hits); })
          .attr("height", function(d) {return height - y(d.hits); });  
}

Is there a way to solve my problem and show ticks properly?

Upvotes: 3

Views: 10080

Answers (2)

Andrea
Andrea

Reputation: 1

If you use the d3.time.scale() you have another problem, you can't use x.rangeBand() when you draw the rect.

Upvotes: -1

l3mm0n
l3mm0n

Reputation: 66

You'll need to tell D3 that your axis is a date. Try this:

//assumes the data is sorted chronologically
var xMin = data[0].dateFieldName;
var xMax = data[data.length-1].dateFieldName;

//set the scale for the x axis
var x = d3.time.scale().domain([xMin, xMax]).range([0, width]); 

//straight from your code
var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")            
        .ticks(d3.time.months, 1)
        .tickFormat(d3.time.format('%b %Y'))

The trick here is to use the d3.time.scale() method.

Upvotes: 5

Related Questions