D3 更新条形图

D3 Update bar chart

所以我对 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);
};

我的问题出现在我将其标记为 "Undefined" 的地方。 graphElement.selectAll(".bars") returns "rects" 的数组,但 .data(data) 调用未定义。

如有任何建议,我们将不胜感激!

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

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);