Skip to content
Advertisement

D3 update color based on data

I’m drawing and coloring lines based on data with D3. I now want to update the color of these lines based on different features in the same data set but my color-changing function (colorP2) does not work–I know this color change looks useless, but it will later be triggered by a button.

Any ideas? Below is my code.

[Update] There was an error in the code that was unrelated to my question, as pointed out by Andrew Reed, which I fixed and marked in the code below.

index.html

JavaScript

drawLines.js

JavaScript

test.geojson

JavaScript

Advertisement

Answer

Solution

Ultimately, you don’t need to join any data in the color changing function: the elements already exist with the data bound to them. The join is intended to ensure one DOM element exists for every item in your data array. Instead, just select the elements and change their attributes/styles:

JavaScript

Problem

I have a strong suspicion that you haven’t quite shared your exact code – if you have, nothing should be drawn as the paths will be placed in a non-valid SVG element: <undefined></undefined>.

Normally you could use a join to reselect elements (even if it was not needed), because it returns both enter and update selections. But you aren’t using selection.join() correctly here. When first adding the paths, you’d normally specify the type of element you want to join as the parameter passed to .join, rather than using selection.append():

JavaScript

Not specifying the type of element you want to create will create an element as follows: <undefined></undefined>. The source code shows how elements are entered in the join statement:

JavaScript

Where onenter is the first parameter passed to .join.

As you haven’t specified a valid SVG element, SVG doesn’t know how to render it, or its children (the path):

JavaScript
JavaScript

Ultimately you should be using .join("path") – for comparison, the following breaks down what happens with each of:

  • selection.join()
  • selection.join().append(“p”)
  • selection.join(“p”);

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement