2014-09-01 101 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)); 
}); 
相關問題