所以我对 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") 返回一个“矩形”数组,但 .data(data) 调用未定义。
如果您能提供任何建议,我们将不胜感激!
最佳答案
您遇到的问题是您将 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);
关于javascript - D3 更新条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29398581/