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?
d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With