I am experiencing an issue with my d3 force directed graph where the links are not

I am relatively new to d3 and have limited experience with web frontend development. In my current web application project, I am attempting to create a force directed graph. Despite spending several hours trying to make it work, I have been unable to display the links between nodes. I've compared my code to various examples online, but it still doesn't seem to be working. I'm not sure why the edges are not being drawn.

After logging the nodes and links to the console, I noticed that the nodes have additional attributes as mentioned in the d3 documentation, but the links do not. Below is my JavaScript file and the JSON data. I have simplified the JSON data to just three entries in an attempt to troubleshoot the issue.

var height = 1080;
var width = 1920;

var color = d3.scale.category20();

var force = d3.layout.force()
    .linkDistance(-120)
    .linkStrength(30)
    .size([width, height]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);


d3.json("/static/javascript/language_data.json", function(data){

force
    .nodes(data.languages)
    .links(data.language_pairs)
    .start();

var link = svg.selectAll(".link")
  .data(data.language_pairs)
  .enter().append("line")
  .attr("class", "link");

var node = svg.selectAll(".node")
  .data(data.languages)
  .enter().append("circle")
  .attr("class", "node")
  .attr("r", 5)
  .style("fill", function(d) { return color(d.group); })
  .call(force.drag);

node.append("title")
.text(function(d) { return d.language; });

force.on("tick", function() {
  link.attr("x1", function(d) { return d.source.x; })
      .attr("y1", function(d) { return d.source.y; })
      .attr("x2", function(d) { return d.target.x; })
      .attr("y2", function(d) { return d.target.y; });

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

Here is the JSON data:

Based on some examples I have seen, I believe that the source and target values represent index positions from the list of nodes.

{
   "languages":[
      {"language": "TypeScript", "group": 1},
      {"language": "Java",  "group": 2},
      {"language": "VHDL", "group": 3}
   ],
   "language_pairs":[
      {"source": "0", "target": "1", "value": 5},
      {"source": "1", "target": "2", "value": 5},
      {"source": "2", "target": "0", "value": 5}
   ]
}

If I missed any important details, please let me know! Thank you for any assistance!

Answer №1

There are two issues that need to be addressed:

1.) The "language_pairs" source/target indexes should be numbers, not strings. Remove the quotes:

"language_pairs":[
  {"source": 0, "target": 1, "value": 5},
  {"source": 1, "target": 2, "value": 5},
  {"source": 2, "target": 0, "value": 5}
]

2.) The linkDistance and linkStrength parameters need adjustment:

var force = d3.layout.force()
    .linkDistance(-120) // Negative distance doesn't make sense 
    .linkStrength(30) // According to the docs, this should be between 0 and 1
    .size([width, height]);

Check out this example for a solution to these problems.

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

Is there a way to incorporate a text box in javascript that displays the retrieved reference count from the database?

I'm currently working on creating a functionality that retrieves rows with the same ID from a database and displays them in a text box. Below is the PHP code I've written for retrieving all the rows: PHP: <?php include_once('pConfig ...

Disable menu bar | customize menu bar in electronJS

I am developing an Angular application with Electron.js. Due to the specific design requirements of my app, which is browser-based, I do not require or want the default Electron.js menu or menu bar to be displayed. Is there a way to remove it from my app ...

I am struggling to retrieve a value from the angular.forEach function, the flag value is not being obtained. What could be

I'm having an issue with my controller.js file. I can't seem to access the value from the angular.forEach function, specifically the flagvalue isn't being retrieved. Is it because the scope of flagvalue ends when the forEach function complet ...

The format of the JSON string in StringBuilder differs from that of Newtonsoft

Hey there! So, I was using StringBuilder to construct my JSON, but then I came across NewTonSoft in C# and decided to give it a shot. However, I noticed that the JSON output is different when using NewTonSoft. I'm puzzled as to why this would happen. ...

Discovering the method to retrieve files from the public folder via URL in next.js

I am working on a Next.js project where users have the ability to upload images. These images are stored in the public directory. Is there a way for me to access these files using a URL structure like mydomain.com/public/coverimg/image.jpg? Below is my AP ...

Ignore non-array properties at a particular level of JSON nesting

I am attempting to extract Firefox's blacklisted hosts from the specific list it references in order to utilize it for a different browser (Qutebrowser). My use of jq for parsing the JSON data has been fairly successful. #!/bin/sh for term in Adverti ...

Tips for adjusting the width of a Facebook embedded video within its container using ReactPlayer

Has anyone encountered issues with adding an embedded video to a NextJS app using ReactPlayer and Facebook videos? It seems that Facebook does not support the width="100%" attribute, as it always snaps back to 500px. Interestingly, this works wel ...

Scheduling classes based on their index or data attributes

Here is a code snippet demonstrating the use of a variable instead of a hardcoded value: var i = 1; if ($(this).attr('data-target="1"')){} To pass the variable i instead of 1, you can modify the code like this: if ($(this).attr('data-targ ...

What is the trick to ensuring that the bind submit function always works consistently instead of sporadically?

I am attempting to compare two values (min - max) from two input fields. If the min value is greater than the max value, an alert message should be displayed... The issue arises when I correct the max value and submit again, as it continues to show the sa ...

Do not need to refresh the form

I developed a PHP-based Feedback form that includes a Popup from Foundation 5. <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style type="text/css"> .auto-style1 { margin-left: 1px; ...

Getting a file object with v-file-input in Nuxt.js

For my Nuxt.Js apps, I utilized Vuetify.js as the UI framework. In order to obtain the file object when uploading files, I incorporated the v-file-input component from Vuetify.js and wrote the following code snippet: <template> <div> ...

A guide on updating object values within an array using map in React

Is there a method to calculate the total sum of specific values from an array of objects? Example array: const exampleArray = [ {item_id: 1, quantity: "3"}, {item_id: 2, quantity: "5"}, {item_id: 3, quantity: "2"} ] In this case, I want to add up the qua ...

Guide on sending JSON data in an HTTP request for Windows Phone

Does anyone know the best way to send or post a JSON HTTP request in Windows Phone 7? I have been using XML HTTP requests successfully for sending and posting with parameters. However, when I attempt to use JSON, I encounter errors. Can someone advise me ...

What is the most effective method for refreshing a control following an Ajax request?

I am currently working on a website that sends an Ajax request to save data to a database. I would like to update the webpage to show the user that their changes have been successfully submitted. I have brainstormed three possible solutions: Immediately ...

Arrange images in a fluid manner around other images

Check out the website I'm currently working on: metroweb.tk I'm in the process of designing a website that mimics the Windows 8 metro UI. However, I've encountered an issue with larger app icons such as notes and clocks sticking out. Is the ...

What reasons could explain why the more efficient approach of offering an initial portion of data is not faster in practice?

My website contains numerous pages with a plethora of small images that need to be loaded. To enhance user experience, I devised two methods to first display a subset of the content without waiting for the entire page to load. The data is stored in a .json ...

Personalize the error message for throwing an exception in JavaScript

I've been working on customizing error messages for exceptions thrown in JavaScript. Despite my best efforts, I have not been successful so far. I'm currently attempting the following code snippet but it's not functioning as expected: f ...

The necessary attribute is malfunctioning. (HTML)

I am currently working on a signup page utilizing HTML and JavaScript. Everything was running smoothly until I added a function to navigate the user to the next page. The issue arises when the textboxes are left blank; upon clicking the button, the user is ...

checkbox revision

I'm attempting to update some text indicating whether or not a checkbox is checked. The issue is that when the checkbox is checked, the textbox disappears and the text takes its place. <form name="myForm" id="myForm"> <input type="checkb ...

Using a React PureComponent to pass parameters from a Child component

I am facing an issue with my TodosList component that displays a list of individual Todo components. Below is the code snippet for the Todo component: export class Todo extends React.PureComponent { render() { return ( <li onClick={this.pr ...