Nodes in force-directed graphs are magnetically attracted to the central point

After finding a solution to the issue in this question Insert text inside Circle in D3 chart

I have encountered an unexpected behavior where my nodes are not positioned correctly. I am unsure about which property is controlling the x and y coordinates of my nodes. Recently, I made changes to my code to include a g layer to the circles so that text can also be appended along with shapes.

DATA

UPDATED CODE


        // Updated code snippet will go here
    

UPDATED OUTPUT https://i.sstatic.net/9GSlw.png

EXPECTED OUTPUT https://i.sstatic.net/zF1Ti.png

UPDATED HTML


        <g stroke="#fff" stroke-width="1.5">
           <g class="circle" cx="-35.89111508769784" cy="131.13965804447696">
              <circle class="circle" r="5" fill="#1b9e77"></circle>
              <text class="circleText" dy="0.35em" dx="5">Node: 0</text>
              <title>Node: 0</title>
           </g>
           <g class="circle" cx="70.97799024729613" cy="-195.71408429254427">
              <circle class="circle" r="5" fill="#d95f02"></circle>
              <text class="circleText" dy="0.35em" dx="5">Node: 3</text>
              <title>Node: 3</title>
           </g>
           [....]
          </g>
    

Answer №1

To make your code compatible with the new elements you are working with, some adjustments need to be made. Currently, your code assumes that you are dealing with circle elements where you define centers using cx and cy. However, now you are using g elements which have standard x and y coordinates.

Firstly, remove the transform from the g element as it is leftover from the demo code:

const node = svg.append("g")
  .attr("stroke", "#fff")
  .attr("stroke-width", 1.5)
.selectAll(".circles")  
  .data(nodes)
  .enter()
  .append("g")
  .classed('circles', true)

In the ticked() function, update the node transformation code to work with g elements (which do not have cx or cy):

node.attr('transform', d => 'translate(' + d.x + ',' + d.y + ')' )

Demo:

// JavaScript code snippet
var json = {"nodes":[{"id":"0","group":0},{"id":"1","group":1},... 

// D3.js visualization library script import
<script src="//d3js.org/d3.v5.js"></script>
  
// SVG container for visualization
<svg></svg>

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

Delay the execution of @mouseover in Vue: a guide to managing scope

Looking to implement an action only when the user has hovered over a div for at least 1 second. Here's how it's set up: <div @mouseover="trigger"></div> In the script section: data() { return { hovered: false } } m ...

How to send props from a Vue.js component tag in an HTML file

I'm facing an issue with passing props from the HTML to the JavaScript code and then down to a Vue component. Here's a snippet of my index.html file: <div id="js-group-discounts"> <div class="form-group required"> <datepick ...

Activate a monitoring pixel with a click of your mouse

I have a tracking pixel that is typically placed in the body of a "installation success" page: <img src="http://domain.com/adclick.php" width="1" height="1" border="0" /> However, I want to trigger this pixel when someone clicks on a download butto ...

What is the process for turning off express logs on my node.js command line interface?

Recently, I've begun delving into the world of node.js and in an effort to improve my debugging practices, I've decided to move away from relying solely on console.log. Instead, I am exploring the use of debug("test message") for my debugging ...

Is there a way for us to determine the time at which the user last took a screenshot or photo?

I am currently developing a website using Django and I have a unique requirement. I need to access the last image that a user has taken on their phone, without the image being shared by anyone else. The photo must be captured by the user's device itse ...

Create an AngularJS directive that formats the model value for visual display, while retaining the original value in the model

I am facing a challenge in building an AngularJS directive for a currency textbox. The directive should take values (amount and currency code) from the model in the scope and then apply currency formatting to it. I am struggling to build this directive usi ...

"Is it possible to conditionally render a component depending on the state in

One of the challenges I'm facing is customizing a filter icon from MaterialUI. My goal is to change its color to black when a checkmark is checked, and adjust its position accordingly. Additionally, when a box is checked, it should fill in setFilters. ...

Integrate incoming websocket information with state management in React

I am facing a challenge in creating a timeseries plot with data obtained from a websocket connection. The issue arises when new values overwrite the previously stored value in the state variable. const [chartData, setChartData] = React.useState(null) Cu ...

Finding tool for locating object names in JSON

JSON data: [ { "destination": "Hawaii", "Country": "U.S.A", "description": "...and so forth", "images": { "image": [ "hawaii1.jpg", "hawaii2.jpg", ...

Obtain the complete file path using JavaScript

Imagine you have a web application utilizing NodeJS and ReactJS, both working on your local machine. In this setup, NodeJS is capable of accepting files selected from the ReactJS GUI via a simple file upload feature, like so: <input type="file" id="fil ...

Incorrectly resolving routes in the generate option of Nuxt JS's .env configuration file

Having trouble using Nuxt JS's 2.9.2 generate object to create dynamic pages as static files by referencing a URL from my .env file: nuxt.config.js require('dotenv').config(); import pkg from './package' import axios from 'a ...

Retrieve the string data from a .txt document

I am facing an issue with my script that retrieves a value from a .txt file. It works perfectly fine when the value is a number, but when trying to fetch text from another .txt file, I encounter the "NaN" error indicating it's not a number. How can I ...

NodeJS domain error handling failing to catch ReferenceError exceptions

I'm currently facing some challenges with domains in NodeJS. I've set up middleware functions to wrap every call in my web application within a domain in order to capture errors, process them, and return informative error messages. While this se ...

In search of a dropline menu with a comparable style

My search for a menu like the one found on www.ultragraph.co.uk has been exhaustive. I have only come across simple dropline menus, but I am seeking one with hidden sub-menus that reveal upon mouseover similar to ultragraph.co.uk. If anyone has any sugge ...

Steps for creating an asynchronous Redis subscriber invocation

My current setup involves a Redis server within AWS ElastiCache. I am publishing messages to a Redis channel and attempting to retrieve these messages through subscription using a JavaScript script as shown below: const redis = require("redis"); const sub ...

Is it possible to use jQuery to set a value for a form control within an Angular component?

I'm currently working on an Angular 5 UI project. In one of my component templates, I have a text area where I'm attempting to set a value from the component.ts file using jQuery. However, for some reason, it's not working. Any suggestions o ...

Proper Structure for Node System (BASIC)

Overview Recently, I entered the world of Node.js and built some basic back end functionality. However, I realized that everything was clustered in one file (index.js) which led me to explore tutorials on using express router middleware and adapting a mod ...

What is the process for integrating a Browserify library module into a project as a standard file?

I have successfully developed a JavaScript library module with browserify --standalone, passing all tests using npm test. Now, I am working on creating a demo application that will utilize this library module in a browser setting. When I run npm update, th ...

Gradually appear/disappear div element with a delay added

Storing divs in an array and deleting them after appending is my current method. Now, I'm looking to incorporate a fade-in and fade-out effect on each div with a delay. Check out this code snippet : var arr = $(".notification"); function display ...

The button similar to Facebook does not function properly when using fancybox

My photo gallery uses fancybox, and when fancybox is open a like button appears outside the title. However, the Facebook like button doesn't seem to work. Here is my JavaScript code: $(".fancyboxi").fancybox({ padding: 0, openE ...