d3.js: Is it possible to line transition by key in

2020-05-08 06:28发布

问题:

I have data arrays of varying length, with an x value (Years) that is part of a finite number of years, e.g.:

var data = [{Year: 2008, Value: 5}, {Year: 2009, Value: 6}]

or

var data = [{Year: 2007, Value: 8}, {Year: 2009, Value: 10}, {Year: 2010, Value: 11}]

Right now, if I transition from the data set that has more values to the one that has less, the (2007, 8) point gets interpolated to (2008, 5), and it just looks weird. What I want is to interpolate by key (Year in this case).

I understood quite simply how to do it with bar charts with the following tutorial, which simply passes a key function to selection.data in order to bind by key instead of index.

In the case of a line though, you can't seem to be able to pass a key function since the data that you pass must be an array of arrays (The datums are an array of points).

How do you get a similar result when you work with line charts?

回答1:

This depends on the line generator you use. In short, there's no easy way to do this. Here are a few options.

  • Adjust the scale of the graph as well. This will make the transition look less weird.
  • Partition your line into several segments. This way, you can remove one of the segments without affecting the other ones. This may not work depending on what interpolation etc you use.
  • Add dummy elements to pad your data array to always be the same length. May not be suitable depending on your application, as parts of the line would still be drawn for the dummy elements.

It depends entirely on your application which option is most suitable (or there may be another). I would probably try the first one first, as it is easy to implement.



标签: d3.js