Circular arrangement using D3 Circle Pack Layout in a horizontal orientation

I'm currently experimenting with creating a wordcloud using the D3 pack layout in a horizontal format.

Instead of restricting the width, I am limiting the height for my layout.

The pack layout automatically arranges the circles with the largest one in the center and the rest around it. However, when the height is constrained, instead of spreading out horizontally, the circles shrink in size.

Is there a way to prevent the layout from resizing the circles and have them start stacking up on the sides once there is no more space around the larger circle?

I envision something similar to this example: https://i.sstatic.net/nZocQ.jpg

However, my current outcome looks like this: http://jsfiddle.net/v9xjra6c/

This is the code I'm working with:

var width,
    height,
    diameter,
    padding,
    format,
    pack,
    svg,
    node;

var initSizes = function() {
    var dimensions = { width: 900, height: 288 };
    width = dimensions.width;
    height = dimensions.height;
    diameter = Math.min(width, height);
    padding = 12;
    format = d3.format(',d');
};

var initLayout = function() {
    pack = d3.layout.pack()
        .sort(null)
        .size([width, height])
        .padding(padding);
};

var createSVG = function() {
    svg = d3.select('.chart-container').append('svg')
        .attr('width', width)
        .attr('height', height)
        .attr('class', 'bubble');
};

var createBubbles = function() {
    var dataset = pack.nodes(DATA);

    node = svg.selectAll('.node')
        .data(dataset.filter(function(d) { return !d.children; }))
        .enter().append('g')
        .attr('class', 'node')
        .attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')'; });

    node.append('title')
        .text(function(d) { return d.name + ': ' + format(d.value); });

    node.append('circle')
        .attr('r', function(d) { return d.r; });

    node.append('text')
        .attr('dy', '.3em')
        .style('text-anchor', 'middle')
        .text(function(d) { return d.name.substring(0, d.r / 3); });
};

initSizes();

initLayout();

createSVG();

createBubbles();

Any suggestions or help would be greatly appreciated!

Answer №1

If you combine Example1 with Example2, your solution would resemble the merging of these two examples.

From Example 1, I adapted a mechanism to confine the circles within certain boundaries to prevent them from exceeding the height and width of the SVG:

function tick(e) {
      node
          .each(cluster(10 * e.alpha * e.alpha))
          .each(collide(.5))
          //maximum radius is set at 50 to limit the width
          .attr("cx", function(d) {  return d.x = Math.max(50, Math.min(width - 50, d.x)); })
          //maximum radius is set at 50 to limit the height
          .attr("cy", function(d) { return d.y = Math.max(50, Math.min(height - 50, d.y)); });        }

I also introduced a scaling concept for determining the radii:

//based on a data value ranging from 0 to 100, the radius will vary from 5 to 500
var scale = d3.scale.linear().domain([0,100]).range([5, 50]);

Adjust your data according to the format in Example2:

var nodes = data.map(function(d){
  var i = 0,
      r = scale(d.value),
      d = {cluster: i, radius: r, name: d.name};  
  if (!clusters[i] || (r > clusters[i].radius)) {clusters[i] = d;}
  return d
});

The final outcome can be seen here: this

Note: Modifying the height in the code will cause the circles to readjust based on available space.

Note: Experimenting with clustering similar nodes like in this example can yield different results. In my scenario, I formed a single group cluster.

I hope this information proves beneficial!

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

Why isn't Freichat displaying the name of the user who logged in?

After creating my own small social networking site, I decided to add a chat script called freichat. However, I am facing an issue where when a user logs in, their name appears as "Guest102" instead of their actual name. I am quite confused by this problem ...

Setting Up One Stylesheet Based on Local Preferences

I am working on positioning translated text on a webpage. The word NEW in English and NOUVEAU in French need to be centered below a graphic. Since the words have different lengths, I am considering using absolute positioning. The challenge is setting the l ...

The height and rows of a textarea element do not adjust properly to the content in FireFox

Looking for a way to create a textarea with dynamic height that adjusts as the user adds new content? The resize property is set to none and overflow is hidden. It seems to be working correctly in Chrome, but Firefox is presenting some mysterious issues wi ...

What are some ways you could utilize componentDidUpdate to make updates seamlessly without the need to manually refresh the page?

When looking at the data, the letter F represents the number of favorited movies and W indicates the number of watched movies. https://i.sstatic.net/HtGi2.png I have created a button that resets the count of favorited movies to 0. However, in order for t ...

The returned state from setState(prev) seems to be in the opposite order when referencing another useState variable within a useEffect

As part of my interactive chat simulation project, I have implemented a feature where users can click on a button named obj4 to start their chat session. Initially, everything functions smoothly, displaying messages 1-4 in the correct order. However, when ...

Implementing X.PagedList within a modal pop-up window

I have implemented a modal pop-up on a webpage: ... <div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="companySearchModal" aria-hidden="true" id="companySearchModal"> <div class="modal-dialog" role="document"> ...

What causes an image's size to change when it floats within the parent container?

There seems to be a height mismatch issue between the container and the image inside it when the parent is floated, but not the child. However, when both are given the float property, the height matches perfectly. Why is this? <div class="parent">&l ...

Is it possible to compile TypeScript modules directly into native code within the JavaScript data file?

I am seeking a way to break down an app in a TypeScript development environment into separate function files, where each file contains only one function. I want to achieve this using TS modules, but I do not want these modules to be imported at runtime in ...

The responsiveness of Slick Slider's breakpoints is malfunctioning

After implementing a slider using slick slider, I encountered an issue with the width when testing it online and in a normal HTML file. If anyone could assist me in resolving this issue, I would greatly appreciate it. Please inspect the code for both scen ...

Is there a way to transfer textbox value to ng-repeat in AngularJS?

1) The Industry dropdown menu corresponds with a code textbox. Depending on the selected industry, the code will change accordingly. 2) There is a dynamic feature to add or delete Movie Names and Directors' names. In this table, there are three colu ...

What is the best way to create this server backend route?

I'm currently working on a fullstack project that requires a specific sequence of events to take place: When a user submits an event: A request is sent to the backend server The server then initiates a function for processing This function should ru ...

Altering the status of a property in an object, at a specific position within a collection of objects, contained within another object?

Currently using React and having some trouble with the setState hook to update a value deep within an object structure ...

Featuring a visual arrangement of categorized images with AngularJS for an interactive display

As I work on developing a web application with Angular, my goal is to create a grid layout that organizes items by category. Each row will represent a different category. Below is an example of the code structure I have in place: <ion-item ng-repeat="i ...

Discover the correct way to locate the "_id" field, not the "id" field, within an array when using Javascript and the MEAN stack

I am working on an Angular application that connects to MongoDB. I have a data array named books, which stores information retrieved from the database. The structure of each entry in the array is as follows: {_id: "5b768f4519d48c34e466411f", name: "test", ...

Incapable of modifying the text within a div container

I am currently working on a script that translates a Russian forum word by word using TreeWalker. However, there is a specific type of div element that I have been unable to change the text for. That leads to my question: How can I go about changing it? Un ...

Is there a way for me to retrieve the locator value of a webelement?

How can I retrieve the selector value used in a selenium webelement in javascript? Let's say I have the following object: var el = browser.driver.findElement(by.id('testEl')); I want to extract the text 'testEl' from this object ...

Incorporating unique components dynamically using a loop in React

As I delve deeper into learning React and experimenting with some basic concepts, I have encountered a seemingly straightforward issue that has left me stumped. Despite my best efforts to search for a solution online, I have come up empty-handed. The crux ...

Tips for using Selenium and Javascript executor to search through the Canvas system?

Is it possible to automate interaction with a 'graph' created on a canvas? I need to be able to click on elements, drag them, and perform other actions like getting text. Can this be achieved with automation using Selenium and JavaScript executor ...

Issues arising from TypeScript error regarding the absence of a property on an object

Having a STEPS_CONFIG object that contains various steps with different properties, including defaultValues, I encountered an issue while trying to access the defaultValues property from the currentStep object in TypeScript. The error message indicated tha ...

Unable to close window with window.close() method after initially opening it with JS or JQuery

I am currently using an Instagram API that requires users to log out through the link . This link redirects users to the Instagram page, but I want them to be redirected to my own page instead. Although I tried different methods from a previous post on thi ...