Search code examples
javascriptd3.jsgraphdata-visualizationgraph-visualization

How to retain line colors in D3


I have created a multi line chart in D3. Each line gets a specific color according to a color array, as follows:

var colors = ["#357ca5", "#001F3F", "#00c0ef", "#39cccc", "#00a65a", "#605ca8", "#f39c12", "#f56954", "#D81B60", "#d2d6de"];

for (var lineIndex = 0; lineIndex < filteredLines.length; lineIndex++) {
            svg.append("path")
                .datum(<any>filteredLines[lineIndex].data)
                // routine line stuff..
                .style("stroke", colors[lineIndex])

Below the chart, I have legends for each line, clicking on which disables that line and shows up remaining lines. I achieve this using the above filteredLines collection, in which I set isVisible property to true or false according to legend click.

The problem is, once a line is disabled, the above for loop runs through the remaining lines and renders them correctly; but the line color gets set according to the colors[lineIndex] , so it gets a different value every time.

What I want is all lines get the same color every time regardless of it's visible or hidden. How can I achieve this? Should I implement some sort of mapping from line to colors? Any help is appreciated. Thank you.


Solution

  • I would suggest you add colors to your actual line data, rather then getting it via array. Then refer to color like filteredLines[lineIndex].color.

    You would want to attach color info to each line at first time.