简体   繁体   中英

D3 update bar chart - Can't bind new data

Hello I'm new to d3 and I couldn't update the data in my bar chart. I'm creating the bars using following code.

g.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.letter) + 1; })
.attr("y", function(d) { return y(d.frequency); })
.attr("width", x.bandwidth() - 1)
.attr("height", function(d) { return height - y(d.frequency); })

I was able to modify the data using hard coded values:

var bar = svg.selectAll(".bar");

bar.transition().duration(750).data(data).enter()
   .attr("y", function(d) { return 0; })
   .attr("height", function(d) { return Math.random()*100; });

How can i properly bind the new data?

See the snippet below for an example of updating the bar chart with new data programmatically and showing a transition animation in the process.

 var data = [{x:10, y:10, w:50, h:25}, {x:10, y:40, w:150, h:25}, {x:10, y:70, w:70, h:25}]; var g = d3.select("g"); // Bind initial data to empty selection, then use enter() // to access the virtual selection from the data-join // and subsequently append a rect for each virtual selection g.selectAll(".bar") .data(data) .enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return dx; }) .attr("y", function(d) { return dy; }) .attr("width", function(d) {return dw; }) .attr("height", function(d) { return dh; }); var new_data = [{x:10, y:10, w:150, h:25}, {x:10, y:40, w:50, h:25}, {x:10, y:70, w:100, h:25}]; // Bind the new data to the rect objects. Since new_data // is of the same size as number of rects, enter() and exit() // selections from data-join will be empty and the rects // with updated bound data are now available in the default // update selection. g.selectAll(".bar") .data(new_data) // grab the update selection by default .transition().duration(3000) .attr("width", function(d) { return dw; }); // Update the attribute 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <svg width="400" height="400"> <g> </g> </svg> 

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