`Connected circles forming a series in d3`

I am currently working on developing an application where the circles are positioned such that they touch each other's edges.

One of the challenges I am facing is with the calculation for the cx function.

.attr("cx", function(d, i) {
  return (i * 50) + 50; //Math.sqrt(d) ;// + 50; 
})

http://jsfiddle.net/59bunh8u/56/

  var el = $('.serieschart');
  var w = el.data("width");
  var h = el.data("height");


  var margin = {
    top: 65,
    right: 90,
    bottom: 5,
    left: 150
  };

  var svg = d3.select(el[0]).append("svg")
    .attr("class", "series")
    .attr("width", w + margin.left + margin.right)
    .attr("height", h + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  svg.selectAll("circle")
    .data([400, 100, 1000, 300])
    .enter().append("circle")
    .attr("cy", 60)
    .attr("cx", function(d, i) {
      return (i * 50) + 50; //Math.sqrt(d) ;// + 50; 
    })
    .attr("fill", function(d, i) {
      return "#00ccff";
    })
    .attr("r", function(d) {
      return Math.sqrt(d);
    });

Answer №1

Using a "counter" to add values...

let counter = 0;

... and assigning the data to a variable...

const dataValues = [400, 100, 1000, 300];

... for better access to different indices.

Next, for each circle element, we set the cx attribute:

.attr("cx", function(data, index) {
    return index ? (counter += Math.sqrt(dataValues[index - 1]) + Math.sqrt(dataValues[index])) : counter;
})

The ternary operator is used because there is no dataValues[index - 1] for the first circle. Here's the math behind it:

  • For the first circle: return counter, which is zero.
  • From the second circle onwards: add both this circle's radius (Math.sqrt(dataValues[index])) and the last circle's radius (Math.sqrt(dataValues[index - 1])) to counter, then return counter.

Check out the demo below:

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 an option is selected in one dropdown, a list is dynamically populated in another dropdown. However, the entire column then displays the selected row's options in a table format

https://i.stack.imgur.com/q7tMT.png Upon selecting an option from a dropdown within a table row, I make a call to an API to fetch a list of strings into another dropdown field for that specific row. However, the entire column is being populated with that r ...

Issue with Material UI select component not displaying the label text

I've been struggling with Material UI's "Select" for quite some time now - spent about 10 hours trying to make it work the way I want. Any help would be greatly appreciated. This question is connected to a previous one: Select MenuItem doesn' ...

Tips for dynamically assigning unique IDs to HTML form elements created within a JavaScript loop

let count = 0; while (count < 4) { $('#container').append("<div><input type='textbox' class ='left' id='left-${count}'/><input type='textbox' class ='right' id=' ...

Display a message stating "No data available" using HighCharts Angular when the data series is empty

My Angular app utilizes Highchart for data visualization. One of the requirements is to display a message within the Highchart if the API returns an empty data set. I attempted a solution, but unfortunately, the message does not appear in the Highchart a ...

Troubleshooting error in WordPress: Changing innerHTML of dynamically created divs using JavaScript. Issue: 'Unable to set property innerHTMl of null'

I am struggling to modify the innerHTML of a "View cart" button using a dynamically generated div class on my Wordpress/Woocommerce site. In a previous inquiry, I was informed (thanks to Mike :) ) that since JavaScript is an onload event, the class changes ...

The display of the selected input is not appearing when the map function is utilized

I am attempting to use Material UI Select, but it is not functioning as expected. When I use the map function, the default value is not displayed as I would like it to be. However, it does work properly when using the traditional method. *** The Method th ...

Separate JavaScript/ASP statements using commas

I'm having trouble comma-delimiting this line in JavaScript, as I keep encountering errors: <a href="javascript:doSubmit(<%= pound & rs("AdvertiserID")%>, <%=rs("AdvertiserName")%>)"> It's Friday, what can I say... The &l ...

The useContext hook was utilized in conjunction with useReducer, however, a child component is unexpectedly showing an

First and foremost, I want to express my gratitude for your unwavering support. As a newcomer to the realm of ReactJS, I am currently navigating through the development of a concept example for a product store that includes various filters in the form of ...

What is the best way to combine multiple periods into a single range?

I am on a quest to find a way to transform sound frequency into light frequency, essentially turning sound into color. Currently, I have managed to come up with a straightforward formula that converts the sound frequency into the light frequency range: co ...

Error encountered during Ajax request - two files being transmitted instead of one

Can someone assist me with a basic ajax call for a login button? I need help with the form submission and sending the request to a php file to handle the login action. However, I am encountering an issue where two files are being sent instead of one when ...

Exploring the Realm of Angular Controllers and Services: Embracing Triumphs and

Currently in the process of creating a service layer for an existing web app using Angular. I am transitioning $http requests and data manipulation to custom Angular services. While I have a good understanding of Dependency Injection in services, I am enco ...

Is there a way to update a useState in TabPanel without causing a re-render?

For the past few months, I've been immersing myself in React and MUI. Recently, I encountered a problem that has me stumped. The Goal: I receive data from a backend and need to display it for users to edit before sending the changes back to the serv ...

Using the Loop Function in Node.js with EJS Templates

Seeking help with a node.js application that utilizes bootstrap. I am trying to display the bootstrap cards in rows of 3, with each row containing data from my dataset in columns. However, my current implementation using two for loops is leading to repeate ...

The function onClick does not function properly when used with the <p> element, but it works flawlessly with the <button> element

export function SignoutButton() { return ( <p onClick={() => signOut({ callbackUrl: "/" })}> <IoIosLogOut /> Logout </p> ); } I was struggling with a function in my next.js project that wasn't wo ...

How can I change the nested Material UI component style from its parent component?

I am currently incorporating a component from an external library into my project. However, I am facing limitations in customizing its style, especially when it comes to a button that is using material ui styles. Upon inspecting the element, I can see that ...

In the JavaScript example provided, do child classes inherit their parent class prototype?

Here's the code I'm working with: class Rectangle { constructor(w, h) { this.w = w; this.h = h; } } Rectangle.prototype.area = function () { return (this.w * this.h); }; class Square extends Rectangle { construct ...

The error is popping up as I try to deploy my Next.js application on Vercel

warning " > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d0f181c1e095009120d5011121c1914131a501f1c0f3d4f534c534d">[email protected]</a>" has an incorrect peer dependency "react@^16 || ^17" ...

Display the QWebEngineView page only after the completion of a JavaScript script

I am currently in the process of developing a C++ Qt application that includes a web view functionality. My goal is to display a webpage (which I do not have control over and cannot modify) to the user only after running some JavaScript code on it. Despit ...

Utilizing a PHP-scripted multidimensional array in an AJAX success function

I've encountered an issue while trying to access a multidimensional array passed to my AJAX success function. Here's how I'm sending the data: $response = array(); $response['message']['name'] = $name; $response['m ...

What is the best way to combine 4 small triangle pieces in order to create one large triangle?

Is there a way to create an image background with triangle shapes by combining small triangles together? I am interested in making this collection of triangle image backgrounds. Can someone guide me on how to do it?! .block { width: 0; height: ...