2016-10-10 32 views
0

我認爲在做某些d3工作時我會學習一些關於ES6類的知識,所以我創建了一個序號條形圖類(fiddle here)。它顯示多個系列的數據(例如:如何在d3 v4中更新&過渡ordinalScale軸

[ 
    [{"label":"apple", "value" :25}, 
    {"label":"orange", "value": 16}, 
    {"label":"pear", "value":19}], 

    [{"label":"banana", "value" :12}, 
    {"label":"grape", "value": 6}, 
    {"label":"peach", "value":5}] 
]; 

我試圖獲取更新的部分工作(在那裏你提供新的數據和酒吧/軸轉換很好)不幸的是太多的例子代碼是V3 ,這似乎並不像我使用的是V4工作的具體方法是:。

updateData(data){ 
    //get an array of the ordinal labels out of the data 
    let labels = function(data){ 
     let result = []; 
     for(let i=0; i<data.length; i++){ 
      for (let j=0; j<data[i].length; j++){ 
       result.push(data[i][j].label); 
      } 
     } 
     return result; 
    }(data); 

    //loop through the (potentially multiple) series in the data array 
    for(let i=0; i<data.length; i++){ 
     let series = data[i], 
      bars = this.svg.selectAll(".series" + i) 
     bars 
      .data(series) 
      .enter().append("rect") 
      .attr("class", ("series" + i)) 
      .classed("bar", true) 
      .merge(bars) 
      .attr("x", 0) 
      .attr("height", this.y.bandwidth()) 
      .attr("y", (d) => { return this.y(d.label); }) 
      .transition().duration(500) //grow bars horizontally on load 
      .attr("width", (d) => { return this.x(d.value); }); 
     bars.exit().remove(); 
    } 

    //update domain with new labels 
    this.y.domain(labels); 
    //change the y axis 
    this.svg.select(".yaxis") 
     .transition().duration(500) 
     .call(this.yAxis) 
} 

我試圖立足於Mike Bostock's code的更新模式

我得到一個內部來自.call(this.yAxis)的d3錯誤,過渡不生氣te,並且yaxis不更新。此外,酒吧也不轉換。出了什麼問題?

回答

0

幾個問題:

  • 更新scaleOrdinal/scaleBand軸之前更新數據加入,否則棒將無法找到他們的Y比例屬性(y(d.yourOrdinalLabel)。軸代碼因此需要在條碼之前。
  • bars(或其他元素,您加入到數據)應該被聲明爲連接操作的結果,以便它可以與.attr()的視覺屬性被鏈接。 let bars = svg.selectAll(".yourClass").data(yourData);
  • 如果您只打算排除現有數據系列而不添加新數據,那麼在類中使用簡單的update方法更合理。看到更新的小提琴。

Working jsfiddle.