Organizing Data to Create a D3 Tree Layout from a CSV

My CSV file has the following structure

source, target, name, value1 , percentange
  A1      A1      T1    200        3%
  A1      A2      T2    340        4%
  A1      A3      T3    400        2%  

I want to create a tree diagram similar to this D3 Pedigree Diagram

I attempted to flatten the file using this example and made progress, but I'm struggling to include the value and percentage fields in the array so they appear on the node.

Although I've tried various examples, none of them seem to support the complete nesting https://gist.github.com/phoebebright/3176159#file-index-html

D3: use nest function to turn flat data with parent key into a hierarchy

Below is my code, with the objective of ensuring that both value and percentage are displayed at the node.

d3.csv("graph2.csv", function(error, links) {
  if (error) throw error;

  var nodesByName = {};

  // Create nodes for each unique source and target.
  links.forEach(function(link) {
    var parent = (link.source = nodeByName(link.source)),
      child = (link.target = nodeByName(link.target));
    if (parent.children) parent.children.push(child);
    else parent.children = [child];
  });
});

This is where I 'Lose' all the value and percentage data for labeling

// Extract the root node and compute the layout.
var nodes = tree.nodes(links[0].source);

// Create the link lines.
var link = svg
  .selectAll(".link")
  .data(links)
  .enter()
  .append("path")
  .attr("class", "link")
  .attr("d", diagonal);

// Create the node circles.
var node = svg
  .selectAll(".node")
  .data(nodes)
  .enter()
  .append("g")
  .attr("class", "node")
  .attr("transform", function(d) {
    return "translate(" + d.y + "," + d.x + ")";
  });

node
  .append("circle")
  .attr("class", "node")
  .attr("r", 4.5);

I would like to have ALL the values from the CSV file appended to the node here

node
  .append("text")
  .attr("class", "source")
  .attr("x", 8)
  .attr("y", -6)
  .text(function(d) {
    return d.name;
  });

function nodeByName(name) {
  return nodesByName[name] || (nodesByName[name] = { name: name });
}

Answer №1

To store the node in the nodesByName object:

var nodesByName = {};

// Assign parent and child nodes for each unique source and target.
links.forEach(function(link) {
  var parent = (link.source = nodeByName(link.source, link)),
    child = (link.target = nodeByName(link.target, link));
  if (parent.children) parent.children.push(child);
  else parent.children = [child];
});

function nodeByName(name, node) {
  return nodesByName[name] || (nodesByName[name] = { name: name, node: node });
}

You can then access them as follows:

node
  .append("text")
  .attr("class", "source")
  .attr("x", 8)
  .attr("y", -6)
  .text(function(d) {
    var node = nodesByName[d.name].node;
    return d.name + " " + node.value1 + " " + node.percentage;
  });

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

Pass along property to subsequent middlewares in Express

Within my express app, I have implemented auth middleware that identifies the current user based on the session ID. I am seeking a way to "persist" the user object and make it accessible to subsequent middlewares. I attempted attaching the user object to t ...

Loading two different models is not possible with ColladaLoader

Upon running the code snippet below, an error is thrown: Uncaught TypeError: Cannot read property 'x' of undefinedt @ three.min.js:462renderBuffer @ three.min.js:549k @ three.min.js:450render @ three.min.js:561render @ loaderTest.html:46 The er ...

What is the best way to ensure that two objects collide with one another?

Issue Description I am currently working on implementing collision detection for two objects. The goal is to determine if the objects are intersecting by calculating their bounding boxes with Box3 and using the .intersectsBox() function to obtain a boolea ...

Adjust size of background image to fit within ie8 window dimensions

Currently, I'm facing an issue where a Drupal 7 module is used to load a background image, but CSS3 resizing is not supported in IE8. background-image: url('image.jpg'); background-size: cover; I have tried conventional methods like placin ...

JavaScript: Can you clarify the value of this variable using five sets of double quotations?

Could you please review the code snippet below for me? <script type="text/javascript"> function recentpostslist(json) { document.write('<ul class="recommended">'); var i; var j; for (i = 0; i < json.feed.entry.length; i++) { ...

Steps to automatically fill out a form with the last ID retrieved from MySQL upon submission

I am currently developing an order form that will populate data in two MySQL tables: "order" and "order_details." Both tables contain the order_number column. To simplify this process, I have created a third table named "order_num" that stores order number ...

Separate the navbar-brand and nav-items onto separate lines within the Bootstrap 4 navbar

I would like to arrange the navbar-brand and nav-items on separate rows. Put the navbar brand on the first row and the navigation items on the second row Existing code: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="nav ...

Experiencing an unexpected abundance of console logs when implementing React Hooks

I am attempting to retrieve data from an API. The desired result is being obtained, but when I attempt to log it to the console, it logs 4 times. Within my app.js, I am utilizing the fetchData function: import React, {useEffect, useState} from 'rea ...

Is there a way to modify my code to restrict users from liking a post multiple times?

I am currently working on a like system and I have made some progress. However, I am struggling to make it so that the likes only increment once. Does anyone have any insights or suggestions on how to achieve this? I have considered using session variables ...

A guide on utilizing buttons within ion list items to execute actions independently for both the button and the list item

Currently, I have a list item with a button that is displayed based on a certain condition. My issue is that when I click the button, a popup should appear, but instead, it also navigates to the next page in the background. Can someone help me figure out h ...

Having trouble with jQuery events not triggering properly after dynamically inserting elements using an ajax request?

It's strange that all my jQuery events become unresponsive after an AJAX call. When I use a load function, once the JSP reloads, none of the events seem to work properly. Any suggestions? Below is the code that triggers the function call: $('#p ...

Is there a similar feature in jQuery to Prototype's Element.identify?

Are there any built-in jQuery methods or widely accepted default plugins that can automatically assign a unique ID to an element? Or is it necessary to create your own solution for this functionality? I'm seeking the jQuery equivalent of Prototype&apo ...

Cleaning CSV data in PHP

As I reflect on my successful creation of a bulk user import engine for my web application, concerns about its security arise. The thought lingers in my mind - is it truly secure? Despite the flawless functionality, I cannot ignore the fact that the data f ...

the process of increasing the values in an array using Golang

Can you help me add the arrays vertically in golang? example : input: [3, 8, 1] [3, 2, 5] output: [6, 0, 7] input: [7, 6, 7] [2, 5, 6] output: [9, 1, 4, 1] My current code doesn't seem to be working properly: func main() { size := 3 ...

Double execution of code in Swift to validate and store data

After completing a substantial block of code, I've noticed that it runs twice whenever the method containing the code is called. While I can't share the entire complex code due to its sensitive data, I can provide an explanation regarding its str ...

Send the Vue component as an argument to the function

Currently, I am in the process of transferring a project to Vue and utilizing Muuri as a layout manager. In my code, I have the following snippet: grid.add(itemElem, { layout: false, active: false }); The variable itemElem used to be an HTML element c ...

Sorry, we couldn't locate the API route you are looking for

Within my Next.js project resides the file main/app/api/worker-callback/route.ts: import { NextApiResponse } from "next"; import { NextResponse } from "next/server"; type ResponseData = { error?: string }; export async function PO ...

What is the process for integrating three.js code manually into an iframe?

I recently posted a question on Stack Overflow inquiring about how to input code into an iframe without using a file or URL. While I was successful with simple cases like <h1>Hello World</h1>, my ultimate goal is to integrate three.js into thes ...

The file upload button in the problem submission form is malfunctioning, causing the expected pop-up window to not appear

Having an issue with my form validation using the Parsley JS plugin. On pages where the Parsley plugin is active, the form input type="file" is unresponsive. The button animates when clicked but there is no pop up to select a file for upload. Additionally, ...

Navigating through an XML document using the Nokogiri SAX parser

After some research and experimentation, I am faced with the task of extracting specific data from a vast XML file. The structure of the data is as follows: <Provider ID="0042100323"> <Last_Name>LastName</Last_Name> <First_Na ...