D3 How to change a data set based on a dropdown list

I am trying to update / change data for rectangles based on a dropdown list. I tried different things and I do not understand the D3 send function very well. I am grateful if someone can update this code so that I can see how it works in practice. I have 3 datasets with values, and I'm just trying to update the dimensions of the rectangle based on what the user selects in the menu bar.

thank you very much,

<!DOCTYPE html> <html> <head> <title>Menu Bar</title> <script type="text/javascript" src="d3/d3.js"> </script> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width"> </head> <body> <select id = "opts"> <option value="ds1">data1</option> <option value="ds2">data2</option> <option value="ds3">data3</option> <!-- and so on... --> </select> <script type="text/javascript"> var w = 100, h = 100 ; var color = d3.scale.ordinal() .range(["#1459D9", "#daa520"]); var ds1 = [[{x:0,y:12}],[{x:0,y:45}]]; var ds2 = [[{x:0,y:72}],[{x:0,y:28}]]; var ds3 = [[{x:0,y:82}],[{x:0,y:18}]]; var canvas = d3.select("body") .append("svg") .attr("width",100) .attr("height",100) ; var appending = canvas.selectAll("body") .data(ds2) ///trying to make this selection dynamic based on menubar selection .enter() .append("g") .style("fill", function(d,i){return color(i);}) ; appending.selectAll("shape") .data(function (d) {return d;}) .enter() .append("rect") .attr("x",10) .attr("y",10) .attr("width",function (d) {return dy;}) .attr("height",19) ; </script> </body> </html> 
+6
source share
1 answer

The main problem with your script is that d3 code is executed only once. When you have multiple data sets, the d3 template (bind, add, update, remove) should be called every time the data is updated.

Here is a rough outline of what you need:

 // config, add svg var canvas = d3.select('body') .append('svg') .attr('width',100) .attr('height',100) .appeng('g'); // function that wraps around the d3 pattern (bind, add, update, remove) function updateLegend(newData) { // bind data var appending = canvas.selectAll('rect') .data(newData); // add new elements appending.enter().append('rect'); // update existing elements appending.transition() .duration(0) .attr("width",function (d) {return dy; }); // remove old elements appending.exit().remove(); } // generate initial legend updateLegend(initialValues); // handle on click event d3.select('#opts') .on('change', function() { var newData = eval(d3.select(this).property('value')); updateLegend(newData); }); 

Here is a working fiddle that demonstrates how to change data using selection (perhaps it needs to be customized for your needs):

http://jsfiddle.net/spanndemic/5JRMt/

+8
source

Source: https://habr.com/ru/post/970778/


All Articles