Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make sure d3 data element matches id?

Tags:

d3.js

I've got an existing svg with a bunch of polygons. Each polygon has a unique id, and with each id, I have some associated data.

My question is this: If I do the natural d3 join:

d3.selectAll("polygon").data(array_of_data)

Is there anyway to insure that the data element associated with a polygon is the correct one?

Or do I just need to keep the order of the array_of_data the same as the order of the selected polygons?

like image 839
Maus Avatar asked Feb 22 '13 02:02

Maus


People also ask

What do the select () and selectAll () functions in d3 do?

d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument.

What is .attr in d3?

D3 provides the ability to set attributes of a selected element using the attr() function. This function takes two parameters: Attribute Name - For example, "r" to set an SVG circle's radius.

What is data binding in d3?

The data() function is used to join the specified array of data to the selected DOM elements and return the updated selection. D3 works with different types of data like Array, CSV, TSV, JSON, XML etc. You can pass two types of value to the data() function, an array of values (number or object) or a function of data.


1 Answers

D3's data() function takes an optional second argument that is intended to provide just such a correspondence between datum and DOM nodes. Try this:

d3.selectAll('polygon').data(array_of_data, function(d) { return d.id; });

That second argument to data() is a callback function that, when called with a datum, returns the key that binds each DOM node to it's corresponding datum. When you don't provide such a function, D3 is left with no option but to use the index to bind datum to DOM nodes.

like image 94
Ray Waldin Avatar answered Oct 18 '22 14:10

Ray Waldin