2012-08-29 42 views
4

基本的D3.js問題,掌握語法!基本D3.js:創建或更新元素?

我使用D3,我想創建的,如果它不存在軸,或更新它與一個過渡,如果它已經存在。

我目前的代碼在下面,但是這個代碼每次都重新創建軸 - 它不會轉換。我怎樣才能改變它的過渡?

var xAxis = d3.svg.axis().scale(x).orient("bottom").ticks(4).tickSize(6, 3, 0); 

updateGraphAndAxes(initialdata); 

$('#button').click(function() { 
    updateGraphAndAxes(newdata); 
}); 

function updateGraphAndAxes(newdata) { 
    // update x.domain here using newdata, then... 
    svg.append("g") 
    .attr("class", "x axis") 
    .attr("transform", "translate(0," + height + ")") 
    .call(xAxis); 
} 
+0

的回答我的問題人們可能會有所幫助:http://stackoverflow.com/questions/11529389/d3-attaching-data-to-an-axis-for-rescaling/ 11530872個#comment15284589_11530872 – PhoebeB

回答

1

正在關注this example。該方法是這樣的:

var xAxisGroup = null; 

function updateGraphAndAxes(newdata) { 

    var t = null; 

    t = svg.transition().duration(1000);  // Set up transition 

    // update x.domain using newdata... 

    if (!xAxisGroup) { 
     xAxisGroup = svg.append("g") 
      .attr("class", "xTick") 
      .attr("transform", "translate(0," + height + ")") 
      .call(xAxis);   
    } else { 
     t.select('.xTick').call(xAxis);  // Call xAxis on transition 
    } 
}