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

Creating internal utility functions in Angular without exporting them as part of the module can be achieved by following a

Currently, I'm in the process of creating an angular module called MyModule. This module includes several sub-modules. angular.module('MyModule', [ 'MyModule.SubModule1', 'MyModule.SubModule2', 'MyModule.SubMo ...

Difficulty encountered with fetching results using jQuery autocomplete with AJAX as the data source

My autocomplete feature is not working properly with my ajax data source. Here is my code: $("#id_q").autocomplete({ source: function (request, response) { $.ajax({ url: "/search/autocomplete/", dataType: "jsonp", ...

How to eliminate all <style> tags across the board using Regex in JavaScript

Is there a way to utilize regex in JavaScript for removing all instances of <style>, <style type="text/css">, </style>, and <style type="text/css"/>? I want the outcome to only present the CSS without any style tags. The code below ...

Toggling forms with HTML <select> elements: A step-by-step guide

In the process of creating a web application, I am faced with the task of registering users based on their specific category. To accomplish this, I have incorporated a combo-box where users can indicate their user type. My objective is to display an appro ...

Show information from a JSON file using a RecyclerView and CardView

I've been working on displaying data from a json file in a listview using recyclerview and cardview. However, when I launch my app, it only shows a blank screen. I can't seem to figure out what went wrong as there are no errors showing up in Andr ...

pretending to make an ajax call using jQuery

To enhance the user experience of file upload, I have implemented a fake ajax request. When the user clicks submit, the form disappears, a loading graphic appears, and after a few seconds, the page refreshes to display the newly uploaded image. However, e ...

Verifying the timestamp of file submission in a form

My goal is to create an HTML form that allows users to send a file to my server, while also recording the exact time they initiated the file transfer. However, I'm facing an issue where only the time the file is received is being logged, rather than w ...

What is the reason for the inability to input a null byte in a file when using ascii mode with node.js?

Below is the code snippet I have written: var fs = require('fs'); var fp = fs.openSync('binary.txt', "w"); var byte = '\0'; fs.writeSync(fp, byte, null, 'ascii'); However, upon execution, when I check the con ...

Utilizing React with an alternative server-side language

I have a small PHP backend for my website and I want to incorporate React on the front end. However, being new to front-end development and React, I am finding this process confusing as most online examples assume a JavaScript backend with Node modules. W ...

New Trainee - Error: document has not been defined

Encountering an Error message while attempting to run Intern tests from the test files directory. The structure of the directory is as follows: test resources rest pickup.js cashManagement.js gitignore intern.js packages.js ...

Tips on elevating a dragged div above all other elements when utilizing two scrollbars

Currently, I have two horizontal scrollers where I need to drag a div from the upper scroller to the lower scroller. While this functionality is working properly, there is an issue with the dragged div getting lost under the borders of the scroller during ...

Is there a way to obtain the Vimeo Video Id in JSON format similar to the YouTube API?

Utilizing the YouTube API, I am able to retrieve channel data effortlessly. However, when it comes to Vimeo Video, are there any similar methods available? I require a solution resembling this format: https://www.example.com/vimeo-api/search?part=snippet ...

Fill in form fields with values from a JSON object

Sorry in advance, I am not well-versed in php and struggling with this. I have a DB entry in JSON format. My goal is to extract values from this object into input boxes. After using the code: $response = json_decode($row['responseJSON']); whe ...

Parsing and transforming Cyrillic Unicode characters from a JSON file using C++

I have a JSON file containing the following data (as an example): { "excel_filepath": "excel_file.xlsx", "line_length": 5.0, "record_frequency": 2.5, "report_file_name": "\u041f&bs ...

Guide to incorporating HTML within React JSX following the completion of a function that yields an HTML tag

I am currently working on a function that is triggered upon submitting a Form. This function dynamically generates a paragraph based on the response received from an Axios POST request. I am facing some difficulty trying to figure out the best way to inje ...

Is the `beforeEach` function in Jasmine synchronized?

Is it guaranteed that multiple beforeEach functions will always run sequentially? beforeEach(function() {}); beforeEach(function() {}); beforeEach(function() {}); beforeEach(function() {}); beforeEach(function() {}); It appears they do. I conducted a tes ...

Using React for Right-to-Left (RTL) Support

How can RTL (Right-to-Left) support be effectively implemented in React applications? Is there a method to customize default <p> and <span> components for RTL support without the need to rewrite existing components? For instance, using a global ...

I'm puzzled as to why a div tag suddenly becomes invisible when I attempt to link it with a v-for directive in my code

I am facing an issue with the div tag assigned to the log class. My objective is to populate the text using data retrieved from the API response. However, when I attempt to include the v-for directive, the entire div mysteriously disappears from the brow ...

Guide to securely encrypting passwords when transferring from an Android device to a PHP server

As a beginner in programming, I am currently working on a small application running on an Android device that requires user-based information from my PHP web server. My strategy involves using JSON for communication between the phone and the server. The p ...

retrieving a JSON attribute that requires an additional HTTP call

Greetings, I have a dilemma related to Angular and a JSON file that I would like to share. Here is a snippet of the JSON data: { "users": [ { "gender": "male", "title": "mr", "first": "francisco", "last": "medina", "street": "2748 w dallas st", "c ...