The D3 force layout is currently displaying just a single connection

I've been experimenting with a graph that I found in this demo and now I want to modify it to display data from Spotify.

I created a sample JSON file and adjusted the script accordingly for the new data format, everything seems to be working fine except for one issue - my links are not displaying properly, I only see one edge connecting two nodes.

Here is an excerpt of my sample JSON:

{
    "tracks": [{
        "date": "2014-05-11",
        "country": "global",
        "track_url": "https:\/\/play.spotify.com\/track\/7b71WsDLb8gG0cSyDTFAEW",
        "track_name": "Summer",
        "artist_name": "Calvin Harris",
        ...
    }
    {
        "date": "2014-05-11",
        ...
    }],
    "links": [{
        "source": 0,
        "target": 1,
        "weight": 5
    },
    {
      ...
    }]
}

and here's my modified code snippet:

d3.json(
    'latest-new.json',
    function(data) {
    // Declare the variables pointing to the node & link arrays
    var nodeArray = data.tracks;
    var linkArray = data.links;
    console.log(data.links);
    ...
);

Upon examining the code further, it appears that the issue might lie in these lines:

var graphLinks = networkGraph.append('svg:g').attr('class','grp gLinks')
  .selectAll("line")
  .data(linkArray, function(d) {console.log(d); return d.source.id+'-'+d.target.id;} )
  .enter().append("line")
  .style('stroke-width', function(d) { return edge_width(d.weight);} )
  .attr("class", "link");

The problem arises from the fact that d.source.id and d.targer.id are null fields in my data. I am considering replacing them with either track_url or index as temporary identifiers to observe any changes in the output.

Substituting one of these properties results in all nodes being connected to each other, forming a complete graph. It is evident there is a fundamental error in my approach, and despite following similar JSON structures in various examples, the exact source of the problem remains elusive.

Answer №1

When working with the force layout, each link within the links array must specify its source and target nodes in one of two ways:

(i) Assign the indices of the corresponding nodes in the nodes array to the source and target attributes of the link. For example: If the array of nodes is [A,B,C] and there is a link from A -> C, then represent that link as {source: 0, target: 2}

(ii) Use references to the actual nodes for the source and target attributes of the link. For example: If the array of nodes is [X,Y,Z] and there is a link from X -> Z, then represent that link as {source: X, target: Z}

If your links array is already formatted correctly, you simply need to pass it as the data binding when creating the edge lines.

Replacing

data(linkArray, function(d) {console.log(d); return d.source.id+'-'+d.target.id;})
with just .data(linkArray) in the snippet for graphLinks should likely resolve the issue.

Since I didn't have access to the complete code, I recommend testing this solution and informing me if it doesn't solve the problem.

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

Include a character in a tube using Angular

Hey everyone, I have a pipe that currently returns each word with the first letter uppercase and the rest lowercase. It also removes any non-English characters from the value. I'm trying to figure out how to add the ':' character so it will ...

Unique Input Values in Forms

I'm encountering an issue with a basic HTML form connected to a PHP script for processing values. Despite thorough testing, the form is not functioning correctly. Upon inspecting the form markup, I discovered: <form id="delete_item_3_form" action ...

Populate a pandas dataframe with predefined values

I currently have a pre-defined dataframe called df1: import pandas as pd df1 = pd.DataFrame(columns = ["id", "col_a","col_b","col_c"]) Additionally, I possess a JSON file: {'123': {'col_a': 5, 'col_b': "kuku", 'col_c&ap ...

Having trouble connecting the controller variable in AngularJS to the HTML page

I'm struggling with a simple query that doesn't seem to be working for me. When making an Ajax call and retrieving data from the backend, everything seems to be in order. Here's the code snippet: $.ajax({ type: "GET", url: service ...

Adding user inputs to the tail end of API requests in Python

def i(bot,update,args): coin=args infoCall =requests.get("https://api.coingecko.com/api/v3/coins/").json() coinId = infoCall ['categories'] update.message.reply_text(coinId) An issue arises when trying to include the args specifi ...

Ways to access a particular property of a child component object from the parent component

Is there a way to access a child component's "meta" property from the parent component without using the emit method? I am aware of the solution involving an emit method, but I'm curious if there is a simpler approach to achieving this. // Defau ...

Design a captivating Profile Picture form using HTML and CSS styling

In my form, I am looking to include a user's Profile picture which should be displayed in either a circular or rectangular shape. Initially, the image area will show a black background or a placeholder image. When the user clicks on this area, they sh ...

Use AJAX to send a form submission along with an anchor tag

I've been facing a challenge trying to make this work, but unfortunately, I haven't had any success. Typically, all my forms include a submit input, and I handle AJAX submission in the following manner: <script> $("input#submit").click(fun ...

Does anyone have any sample code on processing JSON data from a URL using Modified JavaScript Value in Java?

Could anyone provide some examples on how to handle returned Json data using Modified JavaScript Value? Here is the specific data I require from the json url: { "result": { "data": [ { "name": "page1", "period": "dia", "values": [ { "value": 4, "end_time" ...

New to using JavaScript and JQuery, attempting to position a form underneath an image at a specific URL for the

Hello, I'm having difficulties placing a form below an image with a specific URL. As someone who is still learning JQuery, I am unsure of what mistake I might be making. Is there anyone who can help me figure out what's wrong here? <html> ...

What is the best way to pass an array through router navigate function?

I've searched for a solution in other questions, but nothing has helped me... My goal is to redirect to a URL like this: this.router.navigateByUrl('/products'); I want to pass an array and retrieve it in the component with the active link ...

Access-Control-Allow-Origin does not permit AngularJS Origin http://localhost:8080

I'm working on a web application using AngularJS. It's an admin interface that depends on a json-rpc API hosted on a different domain. When testing in my local environment, I encountered the error "Origin http://localhost:8080 is not allowed by ...

What is the most effective method for inputting a date/time into a Django view?

Looking to create a feature where users can see what events are happening at a specific time. What is the most efficient method to implement this request? For example, if I want to display all current events, should I submit a post request to /events/2009 ...

Delete an item from an array based on its index within the props

I am attempting to remove a specific value by its index in the props array that was passed from another component. const updatedData = [...this.props.data].splice([...this.props.data].indexOf(oldData), 1); const {tableData, ...application} = oldData; this ...

The issue with Firebase's real-time database is that data constantly gets overwritten within a single node

Having an issue with writing data to my Firebase realtime database. Below is the code I am using: firebase.database().ref("ac/0/").set(null); firebase.database().ref("ac/0/").once('value', function(snapshot){ for(var i=0; ...

Storing HTML values in a Meteor database is a common practice for web

Within my meteor project, I have a paragraph in HTML containing a JSON value as follows: {"Active Template Id":"6467","Shirt Brand":"levis","ProductId":"EB301","Brand":"on","Material":"cotton","Price":"1800","Combo Id":"S90"} I am looking to store this v ...

Transforming a string to a Date object using JavaScript

Can someone assist me in converting a PHP timestamp into a JavaScript Date() object? This is the PHP code I use to get the timestamp: $timestart = time(); I need help converting this timestamp into a JavaScript date object. The concept of working with d ...

Node.js expressing caution about the use of backslashes in console logging statements

While this issue may not be considered crucial, I have observed an unexpected behavior when it comes to logging backslashes to the console. To verify the results, please try the following two examples in your terminal. I experimented with versions 0.10 an ...

Tips for organizing nodes after converting XML to JSON: Reconstructing the node order

Currently, I am utilizing eXist-db as an XML/TEI database and Angular for website development. The Angular code is requesting data from the eXist-db, and I have chosen to format the response in JSON. At this stage of testing, I believe JSON is the most sui ...

The replacer argument of the JSON.stringify method doesn't seem to work properly when dealing with nested objects

My dilemma is sending a simplified version of an object to the server. { "fullName": "Don Corleone", "actor": { "actorId": 2, "name": "Marlon", "surname": "Brando", "description": "Marlon Brando is widely considered the greatest movie actor of a ...