Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key function for D3 datum

Tags:

d3.js

I was wondering how would it be possible to associate a certain key function with a datum data binding in D3. This seems to be possible with .data([values[, key]]), but the key is not available as parameter in the .datum([value]) binding.

This becomes particularly relevant when drawing SVG paths in which the updated values are not appended to the end of the data array, but contribute to changes in granularity in the middle.

This example illustrates this case: http://jsfiddle.net/vastur/LtHyZ/1/

Each data point is an [(x),(y)] tuple. The red dots are moving properly according to the key function on the x axis:

.data(lineData, function(d) {return d[0]})

But the line is created using datum() and therefore no key function is associated. Consequently, its line segments move illogically when new data points are added in between.

So, in this example, how to make line vertices move according to the motion of the red dots?

like image 245
vastur Avatar asked May 24 '26 09:05

vastur


1 Answers

The short answer is that this is not possible for the case that you're dealing with. The problem is that there is only a single element (the line), so matching and computing joins doesn't make sense. To achieve the behaviour you want, you would need to specify the same number of support points for both lines.

A slightly more elaborate explanation. The D3 data model relies on binding data points to DOM elements. That is, each data point is matched to exactly one DOM element. The path you're drawing is a single DOM element and therefore has only one data "point" matched to it, the point being an array in this case. You can't use D3's data model for what you want precisely of this -- there's only a single DOM element for the path. Furthermore, SVG paths are entities that cannot be broken easily -- you need an M command to start with and then L commands in your case. You can sort of do it by breaking the line into different segments, but then the animation doesn't work (see here).

The way to achieve what you want would be to preprocess the data to compute any intermediate points.

like image 163
Lars Kotthoff Avatar answered May 28 '26 14:05

Lars Kotthoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!