nuway
nuway

Reputation: 2394

How to force d3's date axis to draw ticks for first and last months that are not full [FIDDLE UPDATED]?

I have a set of dates and values that span 13 months. First date is on Dec 31, 2011 and last is Feb 14 2013.

I need to force d3 to draw first tick as December instead of January,and, preferably, last tick as Mach. How should I approach this? I tried ajusting d3 range by flooring it's Min date value:

var domainXMin = d3.min(dataset, function(d){ return d.x; });
var domainXMax = d3.max(dataset, function(d){ return d.x; });

var domainYMin = d3.min(dataset, function(d){ return d.y; });
var domainYMax = d3.max(dataset, function(d){ return d.y; });


var xScale = d3.time.scale()
    .domain([d3.time.month.floor(domainXMin), domainXMax])
    .range([0, width]);

but that doesn't seem to always work. Is there even a way?

Fiddle

Upvotes: 0

Views: 2279

Answers (1)

Mark
Mark

Reputation: 108537

Use tickFormat:

var monthFormat = d3.time.format("%B");
var xAxis = d3.svg.axis()
    .scale(xScale)
    .orient("bottom")
    .ticks(6)
    .innerTickSize(-height)
    .outerTickSize(0)
    .tickPadding(10)
    .tickFormat(monthFormat);   

You'll probably have to resort to setting your ticks yourself:

.tickValues([
    new Date(2011, 11, 1),new Date(2012, 1, 1),
    new Date(2012, 3, 1),new Date(2012, 5, 1),
    new Date(2012, 7, 1),new Date(2012, 9, 1),
    new Date(2012, 11, 1),new Date(2013, 1, 1)
    ]);

Updated fiddle.

Upvotes: 4

Related Questions