2015-04-01 148 views
0

所以我对D3比较新,但是我一直在解决这个问题几天,没有运气。想知道我是否犯了一个新手的错误。D3更新条形图

我正在尝试创建一个表示音量与时间的关系图,并允许用户使用不同的日期范围更新图表。

function updateVolumeGraph(data, div) { 

//Get the data again 
data.forEach(function(d) { 
    d.startTime = new Date(d.startTime); 
    d.totalVolume = d.totalVolume; 
}); 

//Scale the range of the data again 
x.domain(d3.extent(data, function(d) { return d.startTime;})); 
y.domain([0, d3.max(data, function(d) { return d.totalVolume; })]); 

//Select the section we want to apply our changes to 
var graphElement = d3.select(div).transition(); 

var bars = graphElement.selectAll(".bar").data(data); <<< Undefined 

//Add some bars 
bars.enter().append("rect") 
      .attr("class", "bar") 
       .attr("x", function(d) { return x(d.startTime); }) 
       .attr("y", function(d) { return y(d.totalVolume); }) 
       .attr("height", function(d) { return height - y(d.totalVolume); }) 
       .attr("width", barWidth); 

    svg.select(".x.axis") // change the x axis 
     .duration(750) 
     .call(xAxisVolume); 
    svg.select(".y.axis") // change the y axis 
     .duration(750) 
     .call(yAxisVolume); 
}; 

我的问题来自我标记为“未定义”的地方。 graphElement.selectAll(“。bars”)返回一个“rects”数组,但.data(数据)调用未定义。

任何意见,你可以提供将不胜感激!

+1

'graphElement'是从调用'.transition()'返回的选择。我不确定“转换”选择可以执行“.data()”绑定。尝试将其更改为'var graphElement = d3.select(div)'(即不包含'.transition()')并查看是否改变了事情。 – meetamit 2015-04-01 19:05:39

回答

1

您遇到的问题是您将graphElement设置为调用transition方法的返回值。

var graphElement = d3.select(div).transition(); 

var bars = graphElement.selectAll(".bar").data(data); 

而是链接这些方法,尝试调用它设置graphElement变量之后单独调用。

var graphElement = d3.select(div); 
graphElement.transition(); 
var bars = graphElement.selectAll(".bar").data(data);