software_writer
software_writer

Reputation: 4468

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.

Upvotes: 0

Views: 76

Answers (2)

torresomar
torresomar

Reputation: 2229

I usually keep an object which will map the colours of my desired values and the keys of my data. In my case this is feasible because our data is mainly static. I don't know if this approach will help you.

var colorMapping = {
    a: '#FFFFFF',
    b: '#D2D2D2
}
....
.style("stroke", colorMapping[a])

Upvotes: 1

Don
Don

Reputation: 1334

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.

Upvotes: 1

Related Questions