so here goes. I've spent quite some time on this one - and am really tired - so hopefully something silly hasn't eluded me.
I am using a dataset to create a few lines in a chart. After that, using a legend I want to hide lines while also changing the dataset - so changing opacity won't cut it.
I followed the path of adding a key enabled on each object in my dataset and set it to false in order to be able to filter objects to hide. However, It doesn't work as expected since I cannot exit() the lines properly. Removing the lines completely and binding the dataset again gets the job done but messes with the mapping of the line colors to the legend items.
The problem lies somewhere in the redraw()
function.
Hopefully someone is able to sort out this nightmare!
https://jsfiddle.net/2en21Lqh/2/
I have created a fiddle
I understand your feeling... I hope this answer will help you.
You have a few problems in your code, so I fixed the main ones putting comments along the way. Keep in mind there is still a lot that can be improved in my version, up to you to make it better.
I will update the answer with a few comments detailing my thoughts about how to tackle this piece of code and a link to a useful article or answer here on SO.
Meanwhile check this fiddle, and the code below
If you follow the enter, update, exit pattern you don't need to have two different function to draw and update a chart. The action will be the same, so this means less code duplication. Hence, I removed the first part where you were drawing them at page load
An important thing to get right is piping the data from parent (
<g class="d3-group">
) to child (<path>
). This is happening here:This way your paths will always be drawn by d3 according to the data that you pass to their respective parents, and will always be in sync.
Also, the reason why the mapping legend/lines gets messed up is because of how you are assigning the colors,i.e. by using indexes.
You will always have 3 labels in the legend, but a variable number of lines in the SVG (1, 2 or 3), so you can't rely on indexes to assign colors. I used a method that is far from perfect but gets the job done. You will want to find a more scalable and reliable one.
Let me know if you need any clarification.
A few links that might help:
Here's your code refactored with the following fixes:
d.key
for colors instead of index (to fix the wandering colors).I did not "toggle" the lines using opacity, although that would work as well.