Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set custom x-axis labels in d3 bar charts?

I'm using the d3 crossfilter library on this page:

http://jovansfreelance.com/bikestats/d3/crossfilter.php

If you look at the second graph, you'll see the x-axis has labels 0.0, 0.5, 1.0, ... , 6.0. I need those labels to be days of the week, so 0.0 would be Monday, 0.5 shouldn't be there at all and I don't know why it appeared since there are only whole numbers in the data, 1.0 should be Tuesday etc.

Can anyone tell me how to accomplish this? Note that all 4 graphs call the same function, and I need to modify the labels (hard-coding them is fine) only for this particular graph.

like image 716
robert Avatar asked Mar 26 '13 11:03

robert


2 Answers

You should check out ordinal scales. In the meantime, you can make your own tickFormat quite easily:

var weekdays = ["Mon","Tues","Wed","Thurs","Fri","Sat","Sun"];
var formatDay = function(d) {
    return weekdays[d % 7] + "day";      
}

Then just pass it to the scale, e.g.:

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .tickFormat(formatDay);
like image 180
Chris Wilson Avatar answered Oct 14 '22 15:10

Chris Wilson


In D3 v4 I worked it out the following way:

var data = ["Mon","Tues","Wed","Thurs","Fri","Sat","Sun"]
var xScaleLabels = d3
  .scalePoint()
  .domain(data)
  .rangeRound([50, width - 50]); // In pixels

var axisTop2 = d3
  .axisBottom()
  .scale(xScaleLabels)
  .ticks(data.length);

svg
  .append("g")
  .call(axisTop2)
  .attr("transform", "translate(" + margin.left + "," + height + ")");
like image 1
Santiago Martí Olbrich Avatar answered Oct 14 '22 14:10

Santiago Martí Olbrich