javascript - D3 padding dates and values -
i building simple bar chart d3.time.scale:
var data = [ {"date": new date("1992-05-01 00:00:00"), "value": 10}, {"date": new date("1997-05-01 00:00:00"), "value": 110}, {"date": new date("2007-05-11 00:00:00"), "value": 34} ]; var width = 300; var height = 200; var barwidth = width / data.length; var x_domain = d3.extent(data, function(d) { return d.date; }); var x = d3.time.scale() .domain(x_domain) .rangeround([0, width]); var y = d3.scale.linear() .domain([0, d3.max(data, function(d) { return d.value; })]) .range([height, 0]); var chart = d3.select(".chart") .attr("width", width ) .attr("height", height ) .append("g") .attr("transform", function(d, i) { return "translate(" + * barwidth + ",0)"; }); var bar = chart.selectall("g") .data(data) .enter().append("g") .attr("transform", function(d, i) { return "translate(" + * barwidth + ",0)"; }); bar.append("rect") .attr("class", "bar") .attr("y", function(d) { return y(d.value); }) .attr("height", function(d) { return height - y(d.value); }) .attr("width", barwidth - 1);
jsfiddle here.
one bar per date-value couple - simple. generate dates between each 1 of them , assign them 0 value. best way this?
any welcome
filling in missing dates easy, straight javascript. like:
function adddays(date, days) { var result = new date(date); result.setdate(date.getdate() + days); return result; } function fillindates(data){ // put current data hash efficient retrieval // determine min/max of data var currentdates = {}; var maxdate = new date(-1e15); var mindate = new date(1e15); (var = 0; <= data.length; i++){ if (data[i]['date'] > maxdate){ maxdate = data[i]['date']; } if (data[i]['date'] < mindate){ mindate = data[i]['date']; } currentdates[data[i]['date']]= data[i]['value']; } // loop data , fill in missing dates var filledindates = []; while (mindate < maxdate){ filledindates.push({"date":mindate, "value":currentdates[mindate] ? currentdates[mindate] : 0}); mindate = adddays(mindate, 1); } return filledindates; }
note adddays function here.
getting d3
plot though different story. have 5488 bars, in order math work (to bar widths > 0), need increase plot width 10,000 pixels.
see updated fiddle.
Comments
Post a Comment