D3.js Sunbursts featuring Hierarchical Arcs that display values at each level, providing a comprehensive view beyond just the aggregate of the leaves

Hey there, Stackoverflow community!

I've been working on creating a sunburst chart using the resources provided at: http://bl.ocks.org/kerryrodden/7090426. I've successfully replicated the artwork from the example, but now I'm trying to add my own unique twist and facing some challenges. I believe the key lines of code that I need to focus on are:

var partition = d3.layout.partition()
.sort(null)
.size([2 * Math.PI, radius * radius])
.value(function(d) { return d.size; });

I've experimented with different variations of the line:

.value(function(d) { return d.size; });

This includes attempting to modify the values of each parent node to a predefined value sent over in the JSON data. My goal is to have the chart reflect the structure of the JSON data like so:

{
"name": "root",
"children": [
  {
    "name": "a",
    "size": 100,
    "children": [
      {
        "name": "b",
        "size": 50,
        "children": [
          {
            "name": "c",
            "size": 25
          },
          {
            "name": "d",
            "size": 15
          },
          {
            "name": "e",
            "size": 35,
            "children" : [
              {
                "name": "f",
                "size": 10
              },
              {
                "name": "g",
                "size": 5
              }
            ]
          }
        ]
      }
      ]
  }
]
}

In this JSON, each parent object contains the total sum of its children as well as its own value (designated as size). For example, the top parent (root) has a value of 100 because 'a' is also 100. However, when we look at 'b' which is 50 and 'e' which is 35, there's 15 missing from 'b' that is included in 'a''s size. I'm not entirely sure if what I want to achieve is feasible or requires a different approach. When you plug in the JSON above, the chart will render, but upon inspection, 'f' and 'g' represent 100% of 'e', whereas I want them to collectively represent only 42% since the remainder of 'e' should be accounted for by 'f' and 'g'. Thanks for taking the time to read through, and have an awesome day!

Answer №1

Due to my low reputation, I can't leave a comment, so I'll provide an answer instead. Regarding f and g representing 100% together: It appears to be standard behavior for d3.

I suggest modifying your JSON data to ensure all relevant parts are included for display purposes (if that explanation makes sense).

Essentially, if you want f and g to only represent 42%, you must introduce a separate element h with a value of 20. D3 may not automatically infer this - as a data visualization tool, it relies on existing data.

EDIT: Upon review, it seems your current data structure is not ideal. A suggested alternative format could be:

{
"name": "root",
"children": [
  {
    "name": "a",
    "size": 100,
    "children": [
      {
        "name": "b",
        "size": 75,
        "children": [
          {
            "name": "c",
            "size": 25
          },
          {
            "name": "d",
            "size": 15
          },
          {
            "name": "e",
            "size": 35,
            "children" : [
              {
                "name": "f",
                "size": 10
              },
              {
                "name": "g",
                "size": 5
              },
              {
                "name": "h",
                "size": 20
              }
            ]
          }

        ]
      },
      {
        "name":"i",
        "size":25
        }
      ]
  }
]
}

In the adjusted structure, 'i' has been added with a value of 25 to complete element 'a' as follows: a = b + i. While you mentioned parent values matching the sum of children's values, for instance in the case of b having 3 children totalling 75 (25 + 15 + 35), I modified the value of b and introduced element 'i' valued at 25 to achieve the total of 100 for element a. Both element 'i' and 'h' will be visualized by D3 in the sunburst diagram.

Prior to the edit, I also inserted element h with a value of 20.

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

Using Async/Await for Timers within a Loop in Javascript

Currently developing a "Timeblocks" style application for university. The main concept involves having a list of subtasks, each with a specified time limit. The goal is to iterate through these tasks, utilizing a timer to countdown the allocated time and t ...

Implementing dynamic style attachment within a map array function

I am looking to dynamically assign colors to my react component Here are the specific colors I would like to use for this purpose this.color = ["#E91E63", "#2196F3", "#FDD835"] Currently, I am mapping an array in JSX similar to this example { th ...

The <transition> element is not being recognized by VSCode

It seems like my VSCode is highlighting the transition element in red, indicating that it may not be recognizing this element. I'm a bit perplexed by what's happening here. Moreover, the code isn't functioning as expected because there is no ...

JQuery button.click() handler executes without a user click

Currently, I am in the process of tidying up the code for my auction game. However, I have encountered an issue where my function is triggered immediately after endAuction() is called rather than waiting for the button click event. Unfortunately, I am no ...

Utilizing a global variable within a JavaScript function to enable its usage across different PHP pages

In my script, there is a code snippet that sets different grid sizes based on user selection. The goal is to store this selection in a variable that can be accessed in PHP code on another page to tailor the output accordingly. After attempting to add a ne ...

Json File in a Jar Format

Even though I have added the necessary imports to my code, I am still encountering an error with the line: JsonObject obj = new JsonParser().parse(input).getAsJsonObject(); The error message reads: "JsonObject cannot be resolved for a type." import org. ...

What could be the reason for a Python server receiving a JSON message as None?

I'm a beginner in web programming and currently trying to grasp the concept of sending messages between a Python server and a JavaScript client. After stumbling upon a helpful guide at , I learned how to set up a Python server using Flask and send re ...

I am looking to insert a jQuery value or variable into the plugin options

How can I insert a jQuery value or variable into plugin options? This is my current script: $(document).ready(function() { // var bannerheight = 580; if ($(window).width() < 2100) { var bannerheight = 410; var opts = JSON.parse( ...

What is the simplest and least time-consuming method for populating HTML fields with a basic JSON dataset?

I am currently working on a simple software project and I would like to create a set of fields in a jQuery modal dialog. Given certain restrictions, I believe it would be more convenient to utilize jQuery's AJAX functions for communication with the se ...

Appending an empty <li> tag has no effect

I'm facing an issue with this loop where it always generates empty <li></li> tags. Can anyone help me understand why this is happening and suggest a solution? For reference, the loop runs 2 times (verified). function a(){ for (var i ...

The XMLHttpRequest is unable to load the specified URL as the response for preflight contains an invalid HTTP status code of 404

I recently set up a CORS request from my .aspx page and encountered an issue with my Ajax request. Here is the code snippet: $.ajax({ method: 'POST', url: "https://api.example.com/v1/url", data: JSON.stringify('{"auth": {"api_ke ...

Tips for resolving the error message 'Object(...) is not a function' when using ref().set() with Firebase

While attempting to include custom information for a newly registered user in Firebase, I encountered an issue where the ref().set() function is being identified as not a valid function. What could be causing this problem? I have verified that the syntax ...

Is the Flowplayer JS API malfunctioning due to Flowplayer not being properly 'loaded'?

On a webpage, I have implemented multiple videos to autoplay using Flowplayer and jQuery with the following code: $('.video').each(function (k, obj) { $(obj).flowplayer(...) }) These videos are streaming and start playing automatically. At a ...

The header element in the personalized theme is malfunctioning

I'm currently working on a new theme design for Power BI and I've been facing an issue with updating the font color for the header. Even after importing, it doesn't seem to change automatically. Can someone please review my sample below and ...

express-ws is muting all error messages

Utilizing both express and express-ws in a node application has been causing some issues for me. It seems that express-ws is suppressing errors, making it quite challenging to debug my code effectively. To demonstrate the problem I am facing, I have simpl ...

Executing a React asynchronous function within a UseEffect wrapper

I'm having trouble grasping the concept of how an async function operates. It's puzzling to me that the console.log is throwing an error because the data.rates doesn't exist yet. I was under the impression that since the useEffect function ...

Incorporate characteristics into a text box using jQuery

Currently, I am working with asp.net MVC. There is a control that looks like this: <%= Html.TextBox("username") %> I would like to add a lost focus event to this control. This is what I have tried: $(document).ready(function() { $("#username") ...

Retrieving user input through JavaScript and transmitting information using Ajax

UPDATE: Issue resolved by changing name="demo_name" and similar attributes on my form to id="demo_name". Thanks @Jill I'm attempting to save contact form data into a MySQL database using jquery's ajax feature. I'm new to this, and while it& ...

The process of extracting and using JSON data from an existing MySQL database with PHP

My database table used to have a column called data containing JSON data. | data | - `"{"display":{"pageName":"TEBT Home","Name":"rtryrtyrty rtyrtyrtyrty", "Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

Step-by-step guide on uploading a template in unlayer-react-email-editor

<EmailEditor ref={emailEditorRef} onReady={onTemplateReady} /> const onTemplateReady = () => { try { const templateJson = htmlToJSON(savedData?.email?.content); console.log({ templateJson }); emailEditorRef?.current?.editor?. ...