Exploring data with D3 through the art of circle packing

Just starting out with D3 and struggling a bit to grasp the concepts.

I found this tutorial on Zoomable Circle Packing that I'm using:

My main issue is figuring out how to load multiple data sets.

For example, I want something similar to what's shown in this jsfiddle link, but when a button is pressed, I need to load a different .JSON file (with matching names but different values).

I've heard about "Thinking with Joins" by mbostock as a possible solution, but I'm not sure how to implement it.

Any assistance would be greatly appreciated.

Answer №1

To load a json file, you can create a function like this:

var loadJson = function(jsonFile) {
  d3.json(jsonFile, function(error, data) {
    if (error) return console.error(error);

    svg.selectAll("circle").remove();
    svg.selectAll("text").remove();

    var focus = data,
        nodes = pack.nodes(data),
        view;

    var circle = svg.selectAll("circle")
        .data(nodes)
      .enter().append("circle")
        .attr("class", function(d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; })
        .style("fill", function(d) { return d.children ? color(d.depth) : null; })
        .on("click", function(d) { if (focus !== d) zoom(d), d3.event.stopPropagation(); });

    var text = svg.selectAll("text")
        .data(nodes)
      .enter().append("text")
        .attr("class", "label")
        .style("fill-opacity", function(d) { return d.parent === data ? 1 : 0; })
        .style("display", function(d) { return d.parent === data ? null : "none"; })
        .text(function(d) { return d.name; });

    var node = svg.selectAll("circle,text");

    d3.select("body")
        .style("background", color(-1))
        .on("click", function() { zoom(data); });

    zoomTo([data.x, data.y, data.r * 2 + margin]);

    function zoom(d) {
      var focus0 = focus; focus = d;

      var transition = d3.transition()
          .duration(d3.event.altKey ? 7500 : 750)
          .tween("zoom", function(d) {
            var i = d3.interpolateZoom(view, [focus.x, focus.y, focus.r * 2 + margin]);
            return function(t) { zoomTo(i(t)); };
          });

      transition.selectAll("text")
        .filter(function(d) { return d.parent === focus || this.style.display === "inline"; })
          .style("fill-opacity", function(d) { return d.parent === focus ? 1 : 0; })
          .each("start", function(d) { if (d.parent === focus) this.style.display = "inline"; })
          .each("end", function(d) { if (d.parent !== focus) this.style.display = "none"; });
    }

    function zoomTo(v) {
      var k = diameter / v[2]; view = v;
      node.attr("transform", function(d) { return "translate(" + (d.x - v[0]) * k + "," + (d.y - v[1]) * k + ")"; });
      circle.attr("r", function(d) { return d.r * k; });
    }
  });
};

... and then call it using loadJson("flare.json");

Here's an example with multiple json files in action - http://bl.ocks.org/chule/74e95deeadd353e42034

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

The maximum property in a Mongoose schema does not have any impact or

const mongoose = require("mongoose"); const PostSchema = new mongoose.Schema( { user_id: { type: String, required: true, }, content: { type: String, max: 150, required: true, }, }, { timest ...

Using Vue.js and Laravel, you can effectively display values in a dropdown menu

Trying to display a list of countries in a dropdown menu by fetching data from a database using vue.js in laravel 7. However, the countries are not appearing in the dropdown. Code Snippet: <template> <div class="col-md-6 pull-right"> ...

Encountering problem with JSON in the bodyParser function

I've encountered an issue while sending data from my React component using the Fetch API and receiving it as JSON on my Express server. When I try to parse the data using the jsonParser method from bodyParser, I only get back an empty object. Strangel ...

Ways to prevent an image from expanding its width within a container

My webpage features an HTML form that takes user input and PHP code that retrieves images from a specified folder to display them in a slideshow. However, I'm facing an issue where the image width stretches and distorts the appearance of the slideshow ...

Guaranteeing the sequential execution of JavaScript functions

For weeks, I've been struggling with a program that utilizes ajax post methods and dataTables. It has become clear to me that my understanding of how javascript operates is lacking. Below is the javascript code: $('#SaveTimeSheet').click(fu ...

The appropriate use of spacing after text in the context of HTML and

Why is it that when I add padding or margin, no extra space is created after the text? Here is the output: https://i.sstatic.net/1MwjE.png I have tried adding padding and margin after the Stay Tuned text, but it seems to be not working. Any insights on ...

Updating values within a nested JSON file during iteration in JavaScript

I've been looking everywhere for a solution to my problem with no luck... I have a complex nested json object like this: var obj = { a: 1, b: 2, c: { a: 1, b: 2, c: {a: 'hello', b: 'HowAreYou?'} } }; someValue = 'hello'; ...

Tips for retrieving the text enclosed within a <span> tag using jQuery

I am new to jQuery and came across this code online for a questionnaire. I want to save the selected options but I am not sure how to do it. " $.fn.jRadio = function (settings)" What is the purpose of this setting? " var options = $.extend(_de ...

Popup confirming successful subscription to Magento newsletter

Is there a way to create a pop-up message box that appears after the user subscribes to the newsletter? "Your subscription has been confirmed [OK]" I specifically need this functionality to be implemented using JavaScript or jQuery as I want to customi ...

Generating a 3D aircraft model integrated with a point cloud using the three.js library

After creating a pointcloud with all points in the same plane, I am looking to highlight and display it as a rectangle shape when the mouse hovers over. To achieve this, I believe the pointcloud needs to be converted into a mesh. I've spent hours se ...

I'm struggling to get this carousel working properly. It appears on the screen, but the navigation arrows are unresponsive. How can I fix

How do I transform this into a fully functioning carousel that displays 3 or more cards with each spin of the Carousel? Here's a code snippet I've created, but I'm struggling to show multiple cards on different spins. My objective is to have ...

contenteditable -- Utilizing AngularJS to create a block element for the title only

When I click on an input field that is editable, I want the background color to change to white within the box. Can someone please assist me with this? Below is my code: HTML <div id="section{{section.index}}"> <h2 class="title" contentedit ...

Issue encountered when utilizing the childNodes.length attribute in JavaScript with elem

I am struggling to accurately find the count of child nodes in my treeview after implementing drag and drop functionality. Whenever I try to determine the number of child nodes, I keep getting a static value of 4 regardless of the actual number of children ...

Using JsonSerializer to deserialize JSON data containing numerical fields

I am facing a challenge while trying to deserialize the following complex JSON structure (shown in the image). Most deserialization techniques I've come across involve using Dictionary<>, but the issue here is that the "parameters" in this JSON ...

I am encountering an issue with this code. The objective is to determine the frequency at which a specific word appears in the provided paragraph

function processWords(){ text = document.getElementById("inputText").value; text = text.replace(/(^\s*)|(\s*$)/gi,""); text = text.replace(/[ ]{2,}/gi," "); text = text.replace(/\n /,"&bso ...

The present time lags behind in nodejs by a 6-hour difference

I want to compare the current datetime with the datetime stored in a database column. When I use new Date() on my computer, it gives me datetime as 2023-05-21T04:35:07.903Z, even though my computer time shows 10:35:07. How can I resolve this issue? Please ...

How can I prevent dataTable resizing?

Is there a solution to prevent datatable resizing? For instance, when the default number of rows per page in the datatable is set to 10 rows. If you input 13 rows into the datatable, it will be divided into 2 pages - with 10 rows on the first page and 3 ro ...

Bringing Typescript functions into the current module's scope

Is it possible to import and reference a module (a collection of functions) in typescript without the need for the Module. prefix? For instance: import * as Operations from './Operations'; Can I access Operations.example() simply as example()? ...

Error encountered: Unable to serialize bytes object to JSON format in Python 3 when attempting to upload base64 encoded image data

After trying to convert data to JSON for a POST request, I encountered this error: TypeError: Object of type 'bytes' is not JSON serializable Here is my code: dict_data: dict = { 'img': base64.b64encode(urlopen(obj['recognitio ...

Converting the basic logic from if-else statements to foreach loops was unsuccessful

I am currently working with this function: const applyColor = (value) => { let color //shallow to dark const colors = ['#B3E5FC', '#81D4FA' ,'#4FC3F7', '#29B6F6', '#03A9F4', &ap ...