In D3 Hierarchy Typescript, every parent-child duo is assigned the same color

I recently came across an interesting example of the "D3 Collapsible Force Layout" on this website. I decided to tweak the input data a bit:

 const data = {
 "name": "directory",
 "children": [
  {"name": "1st file", 
    "children": [{"name": "1f 1st function", "group": 1},  
    {"name": "1f 2nd function", "group": 1},
    {"name": "1f 3rd function", "group": 1},
    {"name": "1f 4th function", "group": 1}], "group": 1,},
  {"name": "2nd file", "children": [
    {"name": "2f 1st function", "group": 2},
    {"name": "2f 2nd function", "group": 2}], "group": 2},
  {"name": "3rd file", "children": [
    {"name": "3f 1st function", "group": 3}
  ], "group": 3},
  {"name": "4th file", "children": [
    {"name": "4f 1st function", "group": 4},
    {"name": "4f 2nd function", "group": 4},
    {"name": "4f 3rd function", "group": 4}
  ], "group": 4}
 ],
 "group": 0
}

I'm looking to assign specific colors to the parent-child nodes based on their group value. For example, nodes with "group:1" should be red, "group:2" should be green, and so on. Could someone help me achieve this? Appreciate your time and assistance.

Answer №1

Using an ordinal scale simplifies the process. Consider the following example:

const colorScale = d3.scaleOrdinal()
  .domain(d3.range(5))
  .range(d3.schemeDark2);

In this case, a color array called d3.schemeDark2 is used. Feel free to customize it with your preferred colors. Since the groups are numerical, d3.range is utilized for the domain.

To fill the circles with colors:

.style('fill', function(d){
    return colorScale(d.data.group)
})

Below is the updated code with your data and adjustments:

const data = {
  "name": "directory",
  "children": [{
      "name": "1st file",
      "children": [{
          "name": "1f 1st function",
          "group": 1
        },
        {
          "name": "1f 2nd function",
          "group": 1
        },
        {
          "name": "1f 3rd function",
          "group": 1
        },
        {
          "name": "1f 4th function",
          "group": 1
        }
      ],
      "group": 1,
    },
    {
      "name": "2nd file",
      "children": [{
          "name": "2f 1st function",
          "group": 2
        },
        {
          "name": "2f 2nd function",
          "group": 2
        }
      ],
      "group": 2
    },
    {
      "name": "3rd file",
      "children": [{
        "name": "3f 1st function",
        "group": 3
      }],
      "group": 3
    },
    {
      "name": "4th file",
      "children": [{
          "name": "4f 1st function",
          "group": 4
        },
        {
          "name": "4f 2nd function",
          "group": 4
        },
        {
          "name": "4f 3rd function",
          "group": 4
        }
      ],
      "group": 4
    }
  ],
  "group": 0
};

const colorScale = d3.scaleOrdinal()
  .domain(d3.range(5))
  .range(d3.schemeDark2);

const width = 500,
  height = 400;

let i = 0;

const root = d3.hierarchy(data);
const transform = d3.zoomIdentity;
let node, link;

const svg = d3.select('body').append('svg')
  .call(d3.zoom().scaleExtent([1 / 2, 8]).on('zoom', zoomed))
  .append('g')
  .attr('transform', 'translate(40,0)');
...


update()
body {
  background-color: #E6E6E6;
}

svg {
  width: 100vw;
  height: 100vh;
}

.node {
  pointer-events: all;
  cursor: pointer;
  z-index: 1000;
}

.node text {
  font: 8px sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Failure when running npm start command in Nest js

After setting up a fresh Nest js on a new EC2 machine, I encountered an error when trying to run it for the first time. The error message indicated that the npm install process failed abruptly without any visible error: ubuntu@ip-172-31-15-190:~/projects/m ...

TS-Recursive JSON type is not compatible with variables in the node value

As a beginner in Type Script, I am currently working on creating an object with a specific structure: users { "user1" : { "startDate" : <timestamp1> } "user2" : { "startDate" : <timestamp2 ...

Choose the Enum in a dynamic manner

I have three enums Country_INDIA, Country_USA,Country_AUSTRALIA. During runtime, the specific country name is determined (it could be either INDIA, USA, or AUSTRALIA). Is it possible to select the correct enum based on the country name at runtime? For in ...

Determining the exact number of immediate descendants within a ul element, while disregarding any script elements

Here is the HTML structure I am working with, which contains a script tag: <ul id="list"> <li class="item1"><a href="#">Item 1</a></li> <li class="item2"><a href="#">Item 2</a></li> <li ...

Finding the label that is linked to the current DIV or textarea by its "for" property

I am working on a project that involves two elements - a textarea and a div. Each element has a label attached to it using the "for" attribute in HTML. <textarea id="txta_1" class="txta" cols="40" rows="3" onkeyup ...

What could be causing the "Circular structure to JSON" error in Node.js when executing a MySQL query?

Currently, I am working on executing a MySQL query to retrieve all the data from a table named LOGIN. If you navigate to https://localhost:2000/select, and provide the parameter in the req.body as table_name with the value set as login. When making t ...

React/Ionic: Avoiding SVG rendering using <img/> elements

I seem to be encountering an issue when trying to load SVG's in my React/Ionic App. I am fetching weather data from OpenWeatherMap and using the weather?.weather[0].icon property to determine which icon to display. I am utilizing icons from the follow ...

Exploring the power of Angular through the use of promises with multiple

I've come across some forum discussions about angular promises in the past, but I'm having trouble implementing them in my current situation. My backend is nodejs/locomotive and frontend is Angular. In the controller code below, I am trying to a ...

Obtain environment variables within a Strapi plugin

I am currently working on developing a Strapi local plugin, but I am facing an issue with retrieving variables defined in my .env file located at the root of my project. Specifically, I am trying to access this value within my React component (plugins/myPl ...

problem with displaying sidebar in Ember template

Using Ember, I have a login page where I don't want to display the header or sidebar navigation for my site until the user is authenticated. Once they are logged in, I want the header and sidebar to be visible. Currently, I am achieving this by checki ...

Removing characters from a string with regular expressions

I need to eliminate instances of << any words #_ from the given text. stringVal = "<<Start words#_ I <<love#_ kind <<man>>, <<john#_ <<kind man>> is really <<great>> <<end words#_ "; The d ...

Angular 2 feature that allows for a single list value to be toggled with the

Currently, my form is connected to a C# API that displays a list of entries. I am trying to implement a feature where two out of three fields can be edited for each line by clicking a button that toggles between Yes and No. When the button is clicked, it s ...

Retrieve the initial link value in jQuery and make changes to it

Is there a way in jQuery to append to the current value of an attribute without storing it in a variable first? For example: $(document).ready(function() { $("#btn").click(function() { // get the link currently var linkCurrent = $("#link").att ...

Issue encountered with updating canvas texture twice in A-Frame and pdf.js while operating in virtual reality mode

Using the power of A-Frame and pdf.js, I embarked on a quest to build an incredible VR application for viewing PDF files. Everything seemed to be working seamlessly on my desktop - flipping through PDF pages, rendering them onto a canvas, it was a sight to ...

Ways to trigger Bootstrap modal through a PHP GET call

I have been searching for a solution to create a modal similar to this one, but I haven't found anything yet. My requirement is that when we pass true in a GET request, the modal should be displayed. Otherwise, if there is no value specified in the $ ...

Converting a single 10GB zip file into five separate 2GB files with the help of NodeJS

var fs = require('fs'); var archiver = require('archiver'); var output = fs.createWriteStream('./test.zip'); var archive = archiver('zip', { gzip: true, zlib: { level: 9 } // Sets the compression level. }); ...

Enhancing Selectpicker options in Angular using data fetched from a web service

Having trouble with updating a selectpicker element within a subscribe method. I've included the code snippets below: Here is my HTML code: <div class="form-group col-md-2 pull-right"> <label for="city">City</label> <select ...

Exploring the possibilities of integrating JSONP with Framework7

I've been attempting to retrieve images from the Instagram public API using ajax and JSONP: var target = https://www.instagram.com/p/BP3Wu_EDXsjdT5Llz13jFv2UeS0Vw0OTxrztmo0/?__a=1?callback=?'; $$.ajax({ ty ...

Compiler error occurs when trying to pass props through a higher-order component via injection

Recently, I have been experimenting with injecting props into a component using a higher order component (HOC). While following this insightful article, I came up with the following HOC: // WithWindowSize.tsx import React, {useEffect, useMemo, useState} fr ...

Execute local server's unit tests using a Gulp task

I am currently faced with the challenge of running automated unit tests in the terminal for a library application that utilizes the History API internally. To achieve this, I am utilizing Babel to transpile and consolidate my Mocha/Chai/Sinon unit tests in ...