sn4ke
sn4ke

Reputation: 619

d3.js number of days between two dates

I would like to graph the distance between a start date and an end date. I use the x position as my start date and I need the width of my rectangle to be the number of days between start and end. (I think)

Displaying the data this way is not working out as desired: I need the width to END at the end date but it looks like the scale is distorting things. thanks!

var w = 925;
var h = 400;
var padding = 50;

var interactiveViz = d3.select("#viz").append("svg")
    .attr("width", w)
    .attr("height", h);

var minDate = new Date(1999, 1, 27),
    maxDate = new Date(2013, 10, 9);    

var xscale = d3.time.scale()
    .domain([minDate, maxDate])
    .range([0,w]);

var xaxis = d3.svg.axis()
    .scale(xscale)
    .tickFormat(d3.time.format('%Y'))   
    .tickValues([minDate, maxDate]);

interactiveViz.selectAll("rect")
    .data(myData)
    .enter()
    .append("rect")
    .attr("x", function(d) { return xscale(new Date(d.start)) })
    .attr("y", function(d,i) { return i*15 })
    .attr("height", "14px")
    .attr("width", function(d) { return xscale(new Date(d.end)) });

interactiveViz.append("g")
    .attr("class", "x-axis")
    .attr("transform", "translate(0,"+(h-padding)+")")
    .call(xaxis)
    .selectAll("text") 
    .attr("y", "10px")
    .style("fill", "#999999");  

data:

var myData = [
{"country":"name1","start":"1/27/1999","end":"12/8/2000"},
{"country":"name2","start":"1/29/1999","end":"12/21/1999"},
{"country":"name3","start":"12/5/2012","end":"12/18/2012"}
]

Upvotes: 1

Views: 3796

Answers (1)

Adam Pearce
Adam Pearce

Reputation: 9293

You want the width to be equal to the number of pixels between the start date and the end date.

The pixel position of the start date is:

xscale(new Date(d.start))

The pixel position of the end date is:

xscale(new Date(d.end))

The number of pixels between them is

xscale(new Date(d.end)) - xscale(new Date(d.start))

Which is what the width should be equal to

.attr("width", function(d) { return xscale(new Date(d.end)) - xscale(new Date(d.start)) });

Upvotes: 3

Related Questions