Reputation: 2483
I have a simple d3.js time-series graph plotted as SVG circles. The circles are key bound so that when I remove data from end of the array, circles from right are removed and when I remove items from the beginning of the array, circles from left are removed on exit.remove()
.
var circles = svg.selectAll('circle')
.data(data, function(d){return d.key})
Now, I want to do the same with a SVG path. Is there a way to apply key binding to SVG path?
Upvotes: 1
Views: 1048
Reputation: 388
I had a similar issue when I wanted to make a live-updating plot in d3 with an SVG path. d3 uses only one path element for an entire data sequence, i.e. for a given array there is one path drawn that can get very very long depending on your data. This means that d3 cannot simply remove bound data elements by removing DOM elements like circles. It would have to modify something like <path d="M0,0L1,0L2,1L3,2">
to <path d="M1,0L2,1L3,2">
. I do not think d3 has this capability, unfortunately (Though you could code this yourself! You need to override d3.interpolateString and write some custom interpolator that notices the dropped points.)
This also means that you can't use D3's data selector, since data works on a group with multiple elements, like svg circles. You're going to have to use select("#yoursvgpath").datum(data)
instead, which sets the data of a single element, where data is your data array.
Since I knew the hardware my code would run on was fast (desktop i7, ssd, etc...), I simply redrew the path every time I added or removed elements. Even still, it's pretty slow in Firefox (but fine in Chrome), especially when the number of points gets over around 10,000. To redraw, just call datum again and then re-apply your coordinate transformer (something like select("#yoursvgpath").attr("d", line)
where line is your path data transformer). I ended up only redrawing every 5,000 data elements so that the path wasn't constantly being recalculated.
If any of this was confusing, I would definitely read up on making line charts in d3, it's quite a bit different (and less intuitive) than point-based charts. I'd also take a look at https://gist.github.com/mbostock/1642874 and http://bost.ocks.org/mike/selection/, for learning more about d3 selections and line charts.
Upvotes: 2