Error: The function 'enter' cannot be called on the data selection from the SVG append and attribute select statement in the code

I am attempting to replicate the force-directed graph showcased by Bostock in this example https://bl.ocks.org/mbostock/4062045 using my own dataset.

By leveraging Django serializers to parse the JSON-formatted data, I have successfully retrieved the required data from the specified URL within my D3.js code. This project is based on D3 v4.

 <style>

    .links line {
        stroke: #999;
        stroke-opacity: 0.6;
    }

    .nodes circle {
        stroke: #fff;
        stroke-width: 1.5px;
    }

</style>
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

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

    var color = d3.scaleOrdinal(d3.schemeCategory20);

    var simulation = d3.forceSimulation()
        .force("link", d3.forceLink().id(function(d) { return d.se_id; }))
        .force("charge", d3.forceManyBody())
        .force("center", d3.forceCenter(width / 2, height / 2));

    d3.json("../forceLink", function(error, graph) {
        if (error) throw error;

        var link = svg.append("g")
            .attr("class", "links")
            .selectAll("line")
            .data(graph.links)
            .enter()
            .append("line")
            .attr("stroke-width", function(d) { return Math.sqrt(d.value); });

        var node = svg.append("g")
            .attr("class", "nodes")
            .selectAll("circle")
            .data(graph.nodes)
            .enter().append("circle")
            .attr("r", 5)
            .attr("fill", function(d) { return color(d.group); })
            .call(d3.drag()
                .on("start", dragstarted)
                .on("drag", dragged)
                .on("end", dragended));

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

        simulation
            .nodes(graph.nodes)
            .on("tick", ticked);

        simulation.force("link")
            .links(graph.links);

        function ticked() {
            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; });
        }
    });

    function dragstarted(d) {
        if (!d3.event.active) simulation.alphaTarget(0.3).restart();
        d.fx = d.x;
        d.fy = d.y;
    }

    function dragged(d) {
        d.fx = d3.event.x;
        d.fy = d3.event.y;
    }

    function dragended(d) {
        if (!d3.event.active) simulation.alphaTarget(0);
        d.fx = null;
        d.fy = null;
    }

</script>

It appears that there might be an issue with data parsing at the point of .data(graph.links)

For nodes, here is a snapshot of my JSON data: nodes' JSON data

And for links, here is a preview of my JSON data: links' JSON data

Answer №1

It took me 4 full days of investigating, but I finally discovered that the problem was caused by missing "target" values in the data. After deleting those records, everything started working perfectly!

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

When trying to use routes with the .map() function, it does not seem

I am currently working on developing a multi-page web application using react-router-dom. However, I have encountered an issue with the user list page (userlist.js) where the data inside the .map() function is not being returned. Interestingly, the code pr ...

What is the best way to establish a maximum value for variable inputs?

In my Vue form, I have dynamic inputs for issuing shares to shareholders. The user first registers the total amount of shares in the form, then starts issuing this total amount partially by adding dynamic inputs as needed. Finally, the form is submitted. M ...

Using Angular 8.x for routing with customized outlet names

I am attempting to set up routing in my Angular 8.x application, utilizing lazy loading and named outlets. Here is the current configuration: main-layout.html <header> <app-top-menu></app-top-menu> </header> <mat-sidenav-cont ...

Unnecessary socket.io connection in a React component

Incorporating socket.io-client into my react component has been a learning experience. Most tutorials recommend setting it up like this: import openSocket from 'socket.io-client'; const socket = openSocket('http://localhost:8000'); In ...

Hovering over an image and trying to rotate it results in

Check out my rotating image example on hover in React here This effect utilizes scale(), rotate(), and transition properties to create an animated rotation when hovering over the parent element. Additionally, overflow: hidden is applied to the parent elem ...

Using Vue.js and Django Rest Framework to prevent CSRF attacks in the POST method by implementing CSRF Tokens

Attempting to send a POST request from a Vue.js template to my Django API is resulting in a 403 error stating CSRF token missing or incorrect. Since I have separated the front and back end, I do not have a view with {csrf_token} on the Django side. How ca ...

What is the best way to push a variable after employing the split function in JavaScript?

error: An unexpected TypeError occurred while trying to read property 'push'. The error was on this line: " this.name[i].push(arrayData[0]); " I'm confused because the console.log statement before that line shows "data is loaded:" alo ...

The MUI Select component requires two clicks to open its menu if another Select component's menu is already open

I have been developing an application with two dropdowns (Select components) positioned next to each other, denoted as A and B. When A is open and the user intends to click on B to open it, I observed that in the default behavior of material UI, the user ...

The value of req.headers('Authorization') has not been defined

I'm experiencing difficulty with my code as the token is coming back as undefined. Here is the frontend section: export const fetchUser = async (token: any) => { const res = await axios.post('/user/getuser', { headers ...

Using pytest.mark.parametrize with the django.test.SimpleTestCase can streamline your test writing

Currently, I am utilizing pytest version 3.2.2 and Django version 1.11.5 with Python 3.6.2 on a Windows system. When running the following code snippet: import django.test import pytest class ParametrizeTest: @pytest.mark.parametrize("param", ["a", ...

When using Django, it is recommended to use at least four words in 'for' statements. For example, you can use the following syntax for looping

Hello there! This is my first question, and English is not my native language so please bear with me haha So, here's the issue I'm facing - I think it's an identification... well, a structural problem, you could say. The problem at hand: I ...

Is it possible for index.html to reference a .js file in an Angular.js 1.x version?

Authorized users are allowed to access the menu items. While User A requires the menu_1.js file, User B does not need it and should not have access to it. I am trying to determine how to include required js files in index.html for an angular.js version 1 ...

Exploring the world of Next.js version 9.3 and beyond with the exciting addition

As a beginner with Next.js, I am seeking guidance on utilizing getStaticPaths and getStaticProps within catch-all routes. Many blog starters for Next.js 9.3+ focus on single-level blog posts (such as /posts/post-1.md, /posts/post-2.md, etc.), but I am stru ...

Troubuling React Filepond Loading Initial Images Issue

I'm currently facing some challenges while trying to implement Filepond for React. I am attempting to pre-load a user's profile picture upon page load, but have encountered difficulties with two different approaches that I've tried so far: ...

Create a string and introduce 10 unique alterations to it at random locations

Currently, I am faced with the task of modifying a DNA string that is 100 characters long. Specifically, I need to randomly select 20 characters from this string and change them to different characters from a predefined list. import random bases = ("A", ...

Node.js suffering from 'empty post method' issue

I am encountering an issue while retrieving values from certain fields in an index HTML. The post method is returning empty values, with { } being returned instead of the expected email, nick, name, and pass values. Here is my server.js code: var mongoos ...

The method of iterating over a string in key-value pairs

How can I efficiently loop through a string and extract key/value pairs? The data is provided to me as a single string using the jstorage plugin. I attempted to split the string into an array, but the resulting key/values were not as expected. For exampl ...

Modifying Hidden Input Value in Django Form Template to Custom Render Form

Once I have set up MyForm in the forms.py file with a HiddenInput containing a dummy value, my goal is to render as many forms as users stored in my database, each with the username as a hidden input. Django Template: {% for username,time in user_list.it ...

Showing C# File Content in JavaScript - A Step-by-Step Guide

Is there a way to showcase this File (c#) on a JavaScript site? return File(streams.First(), "application/octet-stream", Path.GetFileName(element.Path)); I am looking for something similar to this: <img id="myImg" src="_____&qu ...

Adjusting the image placement within a modal window (using bootstrap 3)

Behold, an example modal: <!-- Large Modal --> <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"> <div class="modal-dialog modal-lg"> <div class="modal-content"> ...