Dragging the force layout, the elements are positioned quite a distance from where they should be

Currently, I am working on a class project that involves multiple data points associated with time. Users should be able to drag these points if they overlap.

The X-axis is fixed to the date while the Y-axis can be adjusted by dragging.

I found an example online and made some modifications, but it seems like the circle and text are not aligned for the same object.

I suspect this issue is related to the tick function:

var ticked = function() {    
    node.attr("transform", function (d) {
    return "translate(" + x(d.date) + "," + d.y + ")";
});

In an attempt to resolve this, I created a different tick function with an altered setup. While the circles now appear in the correct position, unfortunately, the text does not append to them.

data= [
        {id: "Object1", date: "2017-08-21", name: "Object1", count: .4, subtopics: []},
        {id: "Object2", date: "2017-08-22", name: "Object2", count: 1, subtopics: []},
        {id: "Object3", date: "2017-08-25", name: "Object3", count: 2, subtopics: []},  
        {id: "Object4", date: "2017-08-25", name: "Object4", count: 2, subtopics: []},
        {id: "Object5", date: "2017-08-27", name: "Object5", count: 2, subtopics: []},
        {id: "Object6", date: "2017-08-30", name: "Object6", count: 2, subtopics: []},
]

// Additional JavaScript code here

Answer №1

Within your initial code, the `x` position is being applied to the circles:

.attr("cx", function(d) { 
    return x(d.date); 
})

Avoid that: let the `tick` function handle both the `x` and `y` positions.

Below is your modified code with that line removed:

data= [
        {id: "Object1", date: "2017-08-21", name: "Object1", count: .4, subtopics: []},
        {id: "Object2", date: "2017-08-22", name: "Object2", count: 1, subtopics: []},
        {id: "Object3", date: "2017-08-25", name: "Object3", count: 2, subtopics: []},  
        {id: "Object4", date: "2017-08-25", name: "Object4", count: 2, subtopics: []},
        {id: "Object5", date: "2017-08-27", name: "Object5", count: 2, subtopics: []},
        {id: "Object6", date: "2017-08-30", name: "Object6", count: 2, subtopics: []},
]


var r = d3.scaleSqrt()
        .domain([0, d3.max(data, function (d) {
            return d.count;
        })])
        .range([0, 65]);


var margin = {top: 20, right: 20, bottom: 100, left: 50},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var parseTime = d3.timeParse("%Y-%m-%d");
    
data.forEach(function(d) {
      d.date = parseTime(d.date);
      d.close = +d.close;
  });
    
var simulation = d3.forceSimulation()
            .force("charge", d3.forceManyBody().strength(-700).distanceMin(100).distanceMax(1000)) 
            .force("link", d3.forceLink().id(function(d) { return d.index })) 
            .force("center", d3.forceCenter(width / 2, height / 2))
            .force("y", d3.forceY(0.001))
            .force("x", d3.forceX(0.001))
    
    
var svg = d3.select('body').append('svg')
  .attr('width', width + margin.left + margin.right)
  .attr('height', height + margin.top + margin.bottom),
g = svg.append('g')
    .attr('transform','translate(' + margin.left + ',' + margin.top + ')');


var formatNumber = d3.format('');
var x = d3.scaleTime()
.range([0, width]);
x.domain(d3.extent(data, function(d) { return d.date; }));

svg.append("g")
      .attr("class", "axis")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x)
              .tickFormat(d3.timeFormat("%Y-%m -%d")))


var node = g.selectAll('.node')
  .data(data)
  .enter().append('g')
    .attr("class", "node")
    .call(d3.drag()
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended));

node.append('circle')
    .attr('r', function(d) {return Math.max(16, r(d.count)); })
    .style("stroke", "Pink")
    .style("fill", "transparent");      
        
node.append('text')
    .text(function(d){return d.name})
    .attr("text-anchor", "middle")
    .attr("pointer-events", "none");
       

var ticked = function() {
    node.attr("transform", function (d) {
        return "translate(" + x(d.date) + "," + d.y + ")";
    });
}         
    
simulation
    .nodes(data)
    .on("tick", ticked);

function dragstarted(d) {
    if (!d3.event.active) simulation.alphaTarget(0.3).restart();
        d.fx = d.x;
        d.fy = d.y;
}
        
function dragged(d) {
        d.fy = d3.event.y;
}
        
function dragended(d) {
    if (!d3.event.active) simulation.alphaTarget(0);
        d.fx = null;
        d.fy = null;
}
<!DOCTYPE html>
<meta charset="utf-8">
<head>

   
    


</head>

<body style="margin:10px 0">

</div>

<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="./scripts/main.js"></script>

</body>
</html>

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 using express and passport-local, the function `req.isAuthenticated()` will typically return a

I'm seeking some insight into my current situation. I've noticed that whenever I call req.isAuthenticated() in an app.router endpoint, running on port 3001 via the fetch API, it always returns false. It seems like the connect.sid is not being pro ...

Having difficulty in selecting the element

My current challenge involves using Appium to automate a framework I've created. After inspecting an element with Appium inspector, I'm attempting to click on the element within the DOM, even though it's not visible on the device screen. I t ...

Rotating the model from its center after panning the model

Hey there! I've been tinkering around with Three.js and loading JSON models using JSONLoader. I also have TrackballControls.js set up for some basic interaction. However, I've noticed that the rotation behaves differently after moving (PAN) the o ...

Transform your HTML tags into a different format with CKEditor (BBCode format conversion)

Ever since I updated CKEditor, I've been facing an issue with HTML tags being altered. Instead of displaying normally, the tags are changed in the following way: <b> becomes [b] or <p> convert [p] For example: hi Ali => hi [b]Ali[/b] ...

Tips for maintaining the fixed position of the second div despite an increase in the height of the first div

I am looking for assistance with keeping the second <div> in place, even when the height of the first <div> is increased. It's okay if the first <div> overlaps the second one, but I want to ensure that the second div remains stationa ...

When the open button is clicked, the Div will toggle between open and closed states

Recently, some of my questions have not been well-received, which makes me feel a bit disheartened. It's important to remember to be kind when providing feedback. I've noticed that some people downvote without offering constructive criticism, whi ...

What steps can be taken to prevent the controller action if the password and confirm password do not match?

Currently utilizing .Netcore MVC for my project. I am developing a registration page where users are required to input their email, password, and confirm the password. Although I can verify if the entered password matches the confirmation password, the con ...

The map function is not functioning properly following a state update in React

Hey there! I've come across a bit of a dilemma with my map function that I'm using to map a data array within one of the states in my application. Everything seems to be running smoothly upon the initial load, but as soon as I start adding new d ...

Endless Google Locations Instances

My database entries are being displayed in a table using input fields. I want the Location field for each entry to be automatically completed using Google's API. HTML: <input name="edit_airplane[1][location]" type="text" class="airplane_location" ...

Using JSON.parse to convert a JSON list into a JavaScript array is not functioning correctly

By utilizing this function, I am able to fetch a JSON list: $(document).ready(function () { var idContact = @ViewData["IdPhysique"]; var Url = "/Accueil/DonneListeFonctionContact"; $.getJSON(Url, { IdContact: idContact }, function ...

leveraging jquery for delaying, subsequently fading out, and ultimately removing

I am currently working on a website that has a dialog feature which I am trying to make functional by following these steps: The dialog is created using .append() method, then it is set to wait for 5 seconds before fading out and being removed. Despite my ...

positioning two text sections on the left side of an image

I am attempting to create a page layout with text that should look like this: Team Name My Team Name +-------------+ Division Team Division| | Current Ranki ...

Resolving the Issue with onClick Events in Closures

Secrets of the JavaScript Ninja provides an interesting example: HTML <button id="test">Click me!</button> JavaScript var button = { clicked: false, click: function() { this.clicked = true; console.log("this:", this, ...

The $scope in Angular doesn't seem to be working as expected in the callback function, despite using $scope

I'm currently working on converting the JSFiddle found here to AngularJS: http://jsfiddle.net/danlec/nNesx/ Here is my attempt in JSFiddle: http://jsfiddle.net/leighboone/U3pVM/11279/ var onAuthorize = function () { updateLoggedIn(); $scope. ...

struggling to modify hooks variable while fetching multiple URLs in React

I'm currently working on storing data from the TMDB movie API using a custom React hook. useFetch.js import {React, useState, useEffect} from 'react'; export default function useFetch() { const key = process.env.REACT_APP_API_KEY; ...

The art of organizing information: Tables and data management

Looking for a solution with a table: <table> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> </table> Trying to format the cells to display as: 1 2 3 4 ...

Is it possible to assign a width property to a div element?

I want DivTest and IdOtherDIV to have the same width. I attempted to set properties like this: DivTest { background: #007C52; width: document.getElementById("IdOtherDIV").scrollWidth + "px.\n"; } Is there a way to achieve this (considering tha ...

Encountered an exception while trying to retrieve data with a successful status code of 200

Why is a very simple get() function entering the catch block even when the status code is 200? const { promisify } = require('util'); const { get, post, patch, del } = require('https'); //const [ getPm, postPm, patchPm, deletePm ] = [ ...

Having trouble retrieving data from mongo db collection - data not found

For my eCommerce application, I am using MongoDB and Angular. The requirement is to retrieve items under each user in the cart. However, when trying to fetch the data using the object ID as a reference, it seems unable to find any data from the database. ...

Having trouble with JavaScript not functioning correctly within the Update Panel?

Does anyone know how to include JavaScript from a remote source inside an update panel? I'm trying to add Facebook and Twitter share buttons to my application. Here is the code snippet: The problem is that this code works fine when the page is initia ...