简体   繁体   中英

D3 Update bar chart

So I'm relatively new to D3, but I have been trouble shooting this issue for a few days, with no luck. Wondering if I'm making a newbie mistake.

I'm attempting to create a graph which represents volume vs. time, and allow the user to update the graph with a different date range.

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

My issue comes at the place where I have tagged it as "Undefined". graphElement.selectAll(".bars") returns an array of "rects" but the .data(data) call is undefined.

Any advice you could offer would be most appreciated!

The issue you are having is that you are setting graphElement to the return value of you call to the transition method.

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

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

Instead of chaining these methods, try calling it as a separate call after setting the graphElement variable.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM