Create a new chart using completely unique information

I am currently working on implementing the example found at http://bl.ocks.org/mbostock/1093130. The goal is to have the "update" function redraw the graph with a completely different dataset each time a button on the DOM is pressed. I have made some modifications to the example in order to achieve this. Let's say I want to randomly populate the graph with JSON datasets whose names are stored in an array:

var array = ["graph.json","graph2.json"];    
function reload() {
    var rnd = Math.floor(Math.random()*2);
    d3.json(array[rnd], function(error, json) {
        if (error) throw error;

        root = json;
        update();
    });    
}

However, whenever the graph is redrawn, there seems to be a bug where nodes from the previous dataset still appear. I have tried various methods to remove elements from the container before calling update(), but none of them seem to work. After researching, I came across the data() function that uses a join approach to update the graph with changes in the data. Although this approach is useful for dynamic updates, it does not suit my needs. I then tried using datum() instead of data() as it was suggested for non-dynamic layouts, and removed the enter() and exit() calls accordingly. While the code compiles without errors, nothing is rendered on the screen. Here is the updated update() function:

function update() {
  var nodes = flatten(root),
      links = d3.layout.tree().links(nodes);

  // Restart the force layout.
  force
    .nodes(nodes)
    .links(links)
    .start();

  // Update links.
  link = link.datum(links, function(d) { return d.target.id; });

  link.insert("line", ".node")
    .attr("class", "link");

  // Update nodes.
  node = node.datum(nodes, function(d) { return d.id; });

  var nodeEnter = node.append("g")
    .attr("class", "node")
    .on("click", click)
    .call(force.drag);

  nodeEnter.append("circle")
    .attr("r", function(d) { return Math.sqrt(d.size) / 10 || 4.5; });

  nodeEnter.append("text")
    .attr("dy", ".35em")
    .text(function(d) { return d.name; });

  node.select("circle")
    .style("fill", color);
}

Any help or guidance on this issue would be greatly appreciated.

https://i.stack.imgur.com/wzhv5.png

In the image above, you can see that the displayed data does not match the dataset. It should show names like "Mike", "Mike Jr.", "Paul"... and when collapsing nodes by clicking the root node, some of the data gets corrected, but not the data on the root node itself.

Here is the correct data that should be displayed:

//Second graph
{
 "name": "Mike",
 "children": [
  {
   "name": "Mike Jr.",
   "children": [
    {
     "name": "Paul",
     "children": [      
      {"name": "Peter", "size": 743}
     ]
    }
   ]
  }
 ]
}

Answer №1

It seems like you might need a refresher on the fundamental concepts of D3, specifically the enter, update, exit pattern. If you're interested, here is an informative article by Mike Bostock discussing this topic. Below is an image from the article:

https://i.stack.imgur.com/25xUD.png

The key principle is that when making changes to your data, you must rejoin the data:

var circles = d3.selectAll("circle").data(nodes, function(d) { return d.id; });

Afterwards, you can utilize specific functions to determine what has been modified. D3 automates the process of tracking data and HTML elements to identify necessary updates. This allows you to perform actions such as:

circles.enter().append("circle"); // Adding circles for new entries
circles.exit().remove();            // Removing outdated circles from the DOM

Once you invoke enter(), the data items are moved to the update section - where existing data points with representations in the DOM reside. Subsequently, you can apply:

circles.attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; })

Furthermore, it's crucial to pass the key function into .datum() or .data(). Your current implementation appears to include this, so make sure to retain it for effective data management.

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

Creating a new row with a dropdown list upon clicking a button

I want to include a Textbox and dropdown list in a new row every time I click a button. However, I seem to be having trouble with this process. Can someone assist me in solving this issue? Thank you in advance. HTML <table> <tr> ...

How to create a looping animation effect for a div using CSS on hover

Using Bootstrap framework with Wordpress site .test { position: absolute; z-index: 9; left: 50%; height: 10em; width: 10em; margin-left: -5em; background-size: cover; opacity: 0; transition: opacity 0.5s ease; transform: translateY(- ...

Switch out an item within a list of objects with a different item

I have a variable called this.rows that contains a collection of items. There is a real-time item being received from the server, which matches one of the items in the this.rows object collection. How can I replace an item with new values? Below is an ex ...

The spawn function in the child_process module throws an error with the code -2, specifically the

Hey there, I'm working on creating an npx command that allows me to run child commands within my package.json bin: "bin": { "malzahar": "./src/bin/malzahar.js" }, Below is the code from my malzahar.js: #! /usr/bin/en ...

Set a variable in PHP by passing a value

In continuation of my previous post, I realized I missed a point and needed to start a new thread. Thankfully, I found a solution for the issue in my previous post and here is the final code: Scrapping code not working in php <?php $html = file_get_co ...

Is the node certificate store limited to reading only from a predefined list of certificates?

Is there a way to add a new certificate to the list of certificates node trusts, even after some struggle? It appears that Node only trusts certificates hardcoded in its list located here: https://github.com/nodejs/node/blob/master/src/node_root_certs.h ...

Getting js.map Files to Function Properly with UMD Modules

I am experiencing an issue with debugging TypeScript files in Chrome and Firefox. Specifically, when trying to debug the MapModuleTest.ts file, the debugger seems to be out of sync with the actual JavaScript code by two lines. This discrepancy makes settin ...

What is the best way to comprehend this asynchronous exercise with async/await?

Currently, I am working on some exercises related to async/await, and I seem to be stuck on the following problem: The function ​​opA​ should be executed before ​opB​, and ​opB​ should be executed before ​opC​. Arrange the function call ...

Difficulty in detecting variable modifications during testing - Angular2+

After successful login, I expect a certain variable to be updated with the appropriate value. However, during testing, all I see is 'undefined' returned. This variable does change when interacting with the app, showing an error message like &apo ...

Keeping firebase auth while removing firestore from Vue project

I have recently made the switch from Firestore to MongoDB, and I am currently in the process of removing references to Firestore in my App.vue file. However, I am still utilizing Firebase authentication. Upon checking the console error message, I came acr ...

What methods can I use to sort content by its rating?

I am embarking on my inaugural project and attempting to construct a product filtering system. So far, I have successfully implemented search and category filters; however, configuring the rating filter has proven to be challenging. Here is an excerpt of ...

Displaying the current time and total time of a custom video player using Javascript

Currently, I'm in the process of creating an html5 video player and have incorporated javascript to update the current time as a fraction of the total time. The script I've written so far is as follows: function updateTime() { var curTime = ...

What steps can be taken to verify that the submitted data is a legitimate numerical pair?

When I receive a string, it should be in the following format: number,number For example: 34.798,52.123 I need to verify that the number is indeed in this format before assigning it to variables and performing calculations. There is also a concern that ...

When utilizing "Koa-Rewrite," an AssertionError occurs stating that app.use(rewrite) necessitates a generator function

I am currently working with Koa@1 and koa-rewrite@1 to implement a specific functionality. rewritelogic.js const rewrite = require('koa-rewrite'); function rewriteLogic(){ rewrite('/english/experience/dev1', '/english/experienc ...

React's JS is having trouble accepting cookies from the express server

I've encountered an issue where sending cookies from my express server using res.cookie() is not working with the front end. Even though I include {withCredentials:true} in the get requests, the cookies are not being set in the browser's applicat ...

Animate the CSS when the content is within the viewport using pagepiling.js integration

I'm currently working on animating content as it enters the viewport. However, I've encountered an issue where jQuery (used to check if the content is in the viewport) isn't functioning properly alongside pagepiling.js (). I suspect this mig ...

How come my useEffect still contains outdated data?

I have encountered an issue with my useEffect in a React component. Despite having all the necessary dependencies, the state does not update after the useEffect completes. It always displays the previous render. Below is the code snippet of the hook: exp ...

ajax always returns the same value, even when the input value is different

Each time I click on a different value, the console.log keeps giving me the same value. view image description I have checked the HTML code and found that even though each value attribute is different, it still returns the first value of the attribute. vi ...

Tips for creating fonts that adjust depending on the length of characters

Is there a way to adjust the font size of a paragraph based on the space available in its containing div, depending on the length of characters? For instance: p{ font-size:15px; } <div class="caption"> <p>Lorem ipsum dolor sit amet, consect ...

I'm having trouble getting PHP/AJAX to return the expected XML data - it keeps

I have a JavaScript script that looks like this: function showItems(type) { var xmlhttp = new XMLHttpRequest(); //creating object var call = "getitems"; xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState ...