2014-09-01 141 views
0

出于某种原因,我的酒吧(rects)绘图真的很宽 - 我认为它是因为日期不正确解析。这里是D3:无法解析日期与年份

var fakeData= [ 
    {"date":2013-10,"shortFig":10}, 
    {"date":2013-11,"shortFig":-15}, 
    {"date":2013-12,"shortFig":15}, 
    {"date":2014-01,"shortFig":39}, 
    {"date":2014-02,"shortFig":-38}, 
    {"date":2014-03,"shortFig":33}, 
    {"date":2014-04,"shortFig":-35}, 
    {"date":2014-05,"shortFig":-2}, 
    {"date":2014-06,"shortFig":-39}, 
    {"date":2014-07,"shortFig":-46}, 
    {"date":2014-08,"shortFig":23}, 
    {"date":2014-09,"shortFig":45} 
] 

..this数据变为“海图”在我的图表建筑功能,我尝试分析数据,并建立X标尺和X轴代码:

  // parse dates 
      var parseDate = d3.time.format("%Y–%m").parse; 

      thedata.forEach(function(d) { 

       var date = d.date.toString(); 

       d.date = parseDate(date); 
      }); 

      //The X scale 
      var xScale=d3.scale.ordinal() 
       .rangeRoundBands([0, width], .1) 
       .domain(thedata.map(function(d) { return d.date; })); 

      //With the X scale, set up the X axis 
      var xAxis = d3.svg.axis() 
       .scale(xScale) 
       .orient("bottom") 
       .tickValues([thedata[0].date]);    

      //Call the X axis 
      baseGroup.append("g") 
        .attr("class", "xaxis") 
        .attr("transform", "translate(0," + height + ")") 
        .call(xAxis); 

      baseGroup.selectAll("rect") 
        .data(thedata) 
        .enter() 
        .append("rect") 
        .attr("class", function(d){ if(d.shortFig >= 0){return "green3"}else{return "red3"} }) 
        .attr({ 
         "x": function(d) {return xScale(d.date);}, 
         "y": function(d) {return yScale(Math.max(0, d.shortFig));}, //Return the number with the highest value 
         "height": function(d) {return Math.abs(yScale(d.shortFig) - yScale(0));}, //Return the absolute value of a number, so negative numbers will be positive 
         "width": xScale.rangeBand() 
        });  
+0

每个对象上'date'的值应该是一个字符串。 – 2014-09-01 20:30:22

回答

0

只是一个错字,date参数应该是字符串。经过测试,它的工作原理,只需更换fakeData阵列,你应该设置。

var fakeData= [ 
    {"date":"2013-10","shortFig":10}, 
    {"date":"2013-11","shortFig":-15}, 
    {"date":"2013-12","shortFig":15}, 
    {"date":"2014-01","shortFig":39}, 
    {"date":"2014-02","shortFig":-38}, 
    {"date":"2014-03","shortFig":33}, 
    {"date":"2014-04","shortFig":-35}, 
    {"date":"2014-05","shortFig":-2}, 
    {"date":"2014-06","shortFig":-39}, 
    {"date":"2014-07","shortFig":-46}, 
    {"date":"2014-08","shortFig":23}, 
    {"date":"2014-09","shortFig":45} 
]; 

var parseDate = d3.time.format("%Y-%m").parse; 

fakeData.forEach(function(d){ 
    console.log(parseDate(d.date)); 
}); 
相关问题