How to color SVG image based on value from color range using d3?

Viewed 142

I'm trying to create a range of SVG images that represent a member in a team. The number of person svg image show up based on total number of members in the team. Following are some important points:

  • Some members have scores and some don't
  • Each person SVG image represent a member in the team
  • The color for the SVG team should map to the score value
  • The score value ranges from 1 - 5

I've created the stackblitz to show what I've done in Angular and d3 v5. For some reason, the images are not showing in StackBlitz but it works on my local machine.

Ask

The problem I'm facing is that the color on the Person images do not match with the color legend and value. I couldn't figure out why neither how to fix it.

The image currently looks like this:

enter image description here

The data

this.teamScores = [
                          {
                              "memberPersonID": "2892082",
                              "score": 3.8571
                          },
                          {
                              "memberPersonID": "2917522",
                              "score": 3
                          },
                          {
                              "memberPersonID": "2917524",
                              "score": 3.2857
                          },
                          {
                              "memberPersonID": "2917517",
                              "score": 3.2857
                          },
                          {
                              "memberPersonID": "2917520",
                              "score": 3.4286
                          },
                          {
                              "memberPersonID": "2917519",
                              "score": 3
                          },
                          {
                              "memberPersonID": "2917523",
                              "score": 3.1429
                          }
                      ]

Please note the score values and the legend. The colors currently do not seem like it's mapping to the actual score.

1 Answers

The reason that your images weren't coloring was that your colorRange was empty. The reason for that was the following:

var colorRange = d3.range(0, 1, 1.0 / grads.length - 1);

Here, the last argument is calculated as (1.0 / grads.length) - 1 = 0.11111 - 1 = -0.8888, which is a negative number. Therefore the range was empty, which made all persons black.

Changing this to var colorRange = d3.range(0, 1, 1.0 / (grads.length - 1)); fixed it.

Related