Issues with reading d3.js visualization data from a JSON file

I am currently working on a data visualization project using D3.js and I started with a basic framework that I found on this link

The data for my visualization is coming from a json file containing only two values, a string value and an integer. However, I want to include another string value in the visualization below these existing values. Unfortunately, I am struggling to identify the specific changes needed in the d3 code to achieve this.

Below is the snippet of my d3 code:

d3.json("test.json", function(error, root) {
  var focus = root,
      nodes = pack.nodes(root);

  svg.append("g").selectAll("circle")
      .data(nodes)
    .enter().append("circle")
      .attr("class", function(d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; })
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
      .attr("r", function(d) { return (d.r); })
      .style("fill", function(d) { return d.children ? color(d.depth) : null; })
      .on("click", function(d) { return zoom(focus == d ? root : d); });

  svg.append("g").selectAll("text")
      .data(nodes)
    .enter().append("text")
      .attr("class", "label")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
      .attr("fill", "white")
      .style("fill-opacity", function(d) { return d.parent === root ? 1 : 0; })
      .style("display", function(d) { return d.parent === root ? null : "none"; })
      .text(function(d) { return d.name; });

  d3.select(window)
      .on("click", function() { zoom(root); });

  function zoom(d, i) {
    var focus0 = focus;
    focus = d;

    var k = innerDiameter / d.r / 2;
    x.domain([d.x - d.r, d.x + d.r]);
    y.domain([d.y - d.r, d.y + d.r]);
    d3.event.stopPropagation();

    var transition = d3.selectAll("text,circle").transition()
        .duration(d3.event.altKey ? 7500 : 750)
        .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

    transition.filter("circle")
        .attr("r", function(d) { return k * d.r; });

    transition.filter("text")
      .filter(function(d) { return d.parent === focus || d.parent === focus0; })
        .style("fill-opacity", function(d) { return d.parent === focus ? 1 : 0; })
        .each("start", function(d) { if (d.parent === focus) this.style.display = "inline"; })
        .each("end", function(d) { if (d.parent !== focus) this.style.display = "none"; });
  }
});

d3.select(self.frameElement).style("height", outerDiameter + "px");

</script>

Answer №1

It seems like there might be a bit of confusion in your approach, but I believe you were on the right track with your comment Christian. The issue lies in

svg.append("g")
   .selectAll("text")
   .data(nodes)
   .enter()
   .append("text")
   .attr("class", "label")
   .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }) 
   .attr("fill", "white") .style("fill-opacity", function(d) { return d.parent === root ? 1 : 0; })
   .style("display", function(d) { return d.parent === root ? null : "none"; }) 
   .text(function(d) { return d.name; })
   .append("text") //this is the problem
   .text(function(d) { return d.team; });

In the code above, you are inserting a text element into another text element. Take a look at this. Open up the browser debugger and inspect the SVG element. You should observe something similar to:

<svg width="100" height="100">
    <text x="50" y="50" style="fill: #000000;">
        hello
        <text x="50" y="75" style="fill: #000000;">hi!</text>
    </text>
</svg>

What you actually intended was more like

<svg width="100" height="100">
    <text x="50" y="50" style="fill: #000000;">
        hello
    </text>
    <text x="50" y="75" style="fill: #000000;">hi!</text>
</svg>

I hope that clears things up for you!

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

Transforming color images into black and white using JavaScript

     I have implemented this code to convert colored images to grayscale. function applyGrayscaleEffect() {         var imageData = contextSrc.getImageData(0, 0, width, height);         var data = imageData.data;         var p1 = 0.99;   ...

Designing multiple button actions in v-card-actions in Vuetify: A step-by-step guide

Trying to streamline the v-card-actions on my Vuetify v-cards. My aim is to center the test button within the v-card and position it above the like and share "footer" buttons. I want the like and share footer buttons to be at the bottom of the v-card with ...

Error when attempting to open and close a div through a click event

Currently, I am in the process of developing a web service that generates arrays. I am facing an issue where all the div elements on my page load open by default, but I want them to remain closed and only open upon clicking. Specifically, I want a nested d ...

How can I map the content-type */* to application/json on the server side using Resteasy javax?

Issue: I am facing a challenge where I need to change the content-type of */* in the client message to be mapped to application/json on the server side without altering the client code due to many deployed clients. (Changing server code is preferred over c ...

How can I extract information from Firebase and set it in the this.props of a React component?

Hey there, I'm having some trouble with my Firebase setup. I need to transfer data from snapshot.val() into this.props.device, but when I try to do so within the this.firebaseRef.on() function, 'this' is showing up as 'null'. Any s ...

Rotating an object around another object in a 3D matrix axis using Three.js

I currently have the ability to rotate one axis. Here is the code that's working now: https://codepen.io/itzkinnu/full/erwKzY Is there a way to rotate an object on a random axis instead of just one fixed axis? Maybe something similar to this exam ...

Switch up the images based on the JSON response that is received

When receiving a JSON response, I am using the item details to populate a menu grid by utilizing an adapter. So far, I have successfully loaded all the item details such as ImageURL, Description, and Price. However, I encounter an issue when loading the is ...

Determining if a value is an Object Literal in JavaScript: Tips for judging

As someone with limited experience in object type judgment, I find myself unsure of how to determine if a value is an Object Literal in JavaScript. Despite my efforts to search online for answers, I have not been successful. Any guidance or ideas on how to ...

Transforming the hide/show functionality from JQuery to Vue

I created some hide/show panels using jQuery that I want to implement in Vue. However, when I try to integrate the jQuery functions into Vue, the functionality doesn't seem to work properly. The panels are not hiding/showing as expected. Does anyone ...

Text field auto-saving within an iFrame using localStorage is not functioning as expected

My goal is to create a rich text editor with an autosave feature using an iframe. Although each code part works individually, I am struggling to combine them effectively. View LIVEDEMO This graphic illustrates what I aim to accomplish: The editable iFram ...

magnetic container: stationary container nested within absolutely positioned container

I recently created a page that can be viewed here: [LINK] This page is set up to scroll horizontally, resulting in a row of divs with black borders. However, I am facing an issue with the smaller divs inside (red ones). I want them to stay within the par ...

The && symbol in JSONPath: combining conditions efficiently

Here is an example of JSON data taken from the tutorial: { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", " ...

Problem with Material-UI Drawer

Is there a way to make this drawer stay fixed on the page like a sticker and remain active without moving when scrolling? I've tried using docked={false}, but it makes the whole page inactive except for the drawer. Any suggestions on how to solve this ...

The functionality of changing the checkbox to "checked" by clicking on the span is not

How can I create a toggle button with a checkbox using css and jquery? Clicking on the span representing the toggle button should change the checked property of the checkbox. Currently, the span does not change the property, even though it triggers the c ...

Executing a function defined in a .ts file within HTML through a <script> tag

I am attempting to invoke a doThis() function from my HTML after it has been dynamically generated using a <script>. Since the script is loaded from an external URL, I need to include it using a variable in my .ts file. The script executes successfu ...

The request body is not showing up as a key-value pair, while the request headers and other parameters are visible

Example of 'Advanced REST Client' Request I am currently using Postman and Advanced REST client to create a simple POST request based on the code below: 'use strict'; var express = require('express'); var bodyParser = requir ...

Downloading Files Using Ajax and Javascript

When a client makes a request through XMLHttpRequest, the information is sent to the server. The server compiles a CSV file and sends it back as the output stream of the response to the client. Next, the client's browser should display a download dia ...

Sort the data in Angular JS by one key, but ensure that results with another key set to 0 remain at the end

Here is an array of objects containing information about various car brands: $scope.cars = [ {"brand":"McLaren","price":70,"stock":0}, {"brand":"Renault","price":10,"stock":0}, {"brand":"Ferrari","price":100,"stock":3}, {"brand":"Lamborghini","pri ...

"Although the ajax request was successful, the post data did not transfer to the other

i am working with a simple piece of code: var addUser = "simply"; $.ajax({ type: 'POST', url: 'userControl.php', data: {addUser: addUser}, success: function(response){ alert("success"); } }); on the page use ...

What is the best way to dynamically adjust the width of multiple divisions in Angular?

I am currently working on an angular project to create a sorting visualizer. My goal is to generate a visual representation of an array consisting of random numbers displayed as bars using divisions. Each bar's width will correspond to the value of th ...