Working with external data in D3.js involves loading and manipulating datasets efficiently

As a newcomer to D3.js, I have been exploring various tutorials and exercises to familiarize myself with it. My primary goal with D3 is to load external data, typically in JSON format, and create interactive charts based on that data.

You can find the basic sunburst example here:

I managed to adapt it for my own data successfully. However, I am looking for a way to simplify the process of delivering data and handle some manipulation directly within D3.js. For example, instead of providing a hierarchical array specifically designed for a sunburst diagram, I would like to deliver a flat data file that can be manipulated as needed by D3.

Yet, I am uncertain about how to draw a sunburst chart outside of one of D3's data functions. I attempted the code below, where I included the data inline rather than loading it via JSON to make the structure visible (unsurprisingly, it did not work):

var w = 960, 
    h = 700, 
    r = Math.min(w, h) / 2, 
    color = d3.scale.category20c();

var vis = d3.select("#chart").append("svg:svg") 
    .attr("width", w) 
    .attr("height", h) 
       .append("svg:g") 
    .attr("transform", "translate(" + w / 2 + "," + h / 2 + ")");

var partition = d3.layout.partition() 
    .sort(null) 
    .size([2 * Math.PI, r * r]) 
    .value(function(d) { return 1; }); 
var arc = d3.svg.arc() 
    .startAngle(function(d) { return d.x; }) 
    .endAngle(function(d) { return d.x + d.dx; }) 
    .innerRadius(function(d) { return Math.sqrt(d.y); }) 
    .outerRadius(function(d) { return Math.sqrt(d.y + d.dy); }); 
var data = [ 
                        {'level1': 'Right Triangles and an Introduction to Trigonometry', 
'level2': '', 'level3': '', 'level4': '', 'branch': 'TRI', 'subject': 
'MAT'}, 
                        {'level1': '', 'level2': 'The Pythagorean Theorem', 'level3': '', 
'level4': '', 'branch': 'TRI', 'subject': 'MAT'}, 
                        {'level1': '', 'level2': '', 'level3': 'The Pythagorean Theorem', 
'level4': '', 'branch': 'TRI', 'subject': 'MAT'}, 
                        {'level1': '', 'level2': '', 'level3': 'Pythagorean Triples', 
'level4': '', 'branch': 'TRI', 'subject': 'MAT'} 
                        ]; 
console.log(data); // looks good here 
var nest = d3.nest() 
        .key(function(d) { return d.subject;}) 
        .key(function(d) { return d.branch;}) 
        ... 

<p>The HTML code:</p>

<pre><code><div class="gallery" id="chart">
    <svg width="960" height="700">
        <g transform="translate(480,350)">
            <path display="none" d="MNaN,NaNANaN,NaN 0 1,1 NaN,NaNL0,0Z" fill-rule="evenodd" style="stroke: #ffffff; "/>
        </g>
    </svg>
</div>

I sense that I might be overlooking something simple, but struggling to grasp how D3 will interpret all the data and generate the diagram without nesting the drawing functions within a function like d3.json.

Any insights?

Answer №1

Seems like you've overlooked the necessary step of invoking partition.nodes(nest) to set up the data with the correct layout positions for displaying the paths.

In the sunburst example that you provided, the JSON data is linked in this manner:

var path = vis.data([json]).selectAll("path")
    .data(partition.nodes)
  .enter().append("path")
    // …

This can also be achieved by:

var path = vis.selectAll("path")
    .data(partition.nodes(json))
  .enter().append("path")
    // …

Both methods are valid, but it's crucial to call partition.nodes at some point to ensure the data contains position information.

Additionally, keep in mind that your sample data structure with identical nested fields would result in a hierarchy containing only one node.

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

Can you explain the purpose of useEffect in React?

As a beginner in learning React, I have been able to grasp the concept of the useState hook quite well. However, I am facing some difficulties understanding the useEffect hook. I have tried looking through the documentation, searching online, and even wat ...

Should one prioritize learning TypeScript over diving into Angular2?

Should I prioritize learning TypeScript before diving into AngularJS 2? ...

Displaying the second image twice in a jQuery image slider

When attempting to implement a slider on my website, I encountered an issue where the second image appears twice in a row before the slider starts working as expected. I'm struggling to figure out why this is happening. Here is the jQuery code I am u ...

Tips on transforming a JSON file into a response for my personal server

After successfully converting an Excel file to JSON format using my code, I encountered a challenge when trying to convert this as a response. Despite attempting to use res.send in the JS code, it only displayed directory/inner codes instead of a response. ...

Tips for including JSON data in the body of a GET request using Rest Assured

Is it recommended to create a JSON object when trying to pass this specific JSON in the body of a get request using rest assured? { "pharmacyListId": null, "pharmacyListName": "PTA", "customerSetTypeId" ...

Update the Vue method

Is there a way to optimize the following method or provide any suggestions on what can be improved? I am trying to create a function that converts author names from uppercase to only the first letter capitalized, while excluding certain words ('de&apo ...

Unable to render the Google Gauge chart using the provided JSON information

I'm currently facing an issue with implementing Google charts on my website using data from a MySQL database through JSON encoding. Despite ensuring that my JSON encoded data is in the correct format based on various forums, I'm encountering diff ...

Avoiding the <br> tag in list items with TinyMCE

I am currently using tinyMCE and I needed to enable the "force_br_newlines: true" option. Without this setting, if I press the "Enter" key twice and check the source code, I only see one <br> tag. However, when I set the option to TRUE, it creates a ...

What is the best way to keep the textfield value at 0? If you clear the textfield, it will result in another value being

If I don't input anything in this field, the total will show as isNaN, and I want to prevent form submission if it is isNaN. How can I stop the form from being submitted when the total value is isNaN? export default function BasicTextFields() { cons ...

JavaScript sticky navigation bar - error displayed in console

Hey there, I'm having an issue with my Sticky-menu. I've been trying to troubleshoot it but keep getting these console error messages: 1. Cannot read property 'offsetTop' of null at HTMLDocument. 2. Cannot read property 'class ...

What is the best way to ensure type safety in a Promise using Typescript?

It seems that Promises in Typescript can be type-unsafe. This simple example demonstrates that the resolve function accepts undefined, while Promise.then infers the argument to be non-undefined: function f() { return new Promise<number>((resolve) ...

Modify an element upon clicking the mouse on an image

I am looking to dynamically change the paragraph element with className="details" to an editable input field when a user clicks on the image with className="edit-icon" within the same grid container. How can I achieve this functionality ...

Fusion Tables API: JavaScript Integration - resolvable typeError encountered when accessing API in browser

I've been working on extracting data from a Google Fusion Table. Following the Google documentation, I created a JSON file by using the Fusion Tables API with this call: *%20FROM%yyyyyy&key=xxxxxxxxx" Now, I want to integrate this call into a w ...

Easily toggle between different content within the same space using Twitter Bootstrap Tabs feature. Display the tabs

I made a modification to the bootstrab.js file by changing 'click' to 'hover': $(function () { $('body').on('hover.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.p ...

Filtering data based on the model in React Native allows you to refine and organize

This code snippet represents a modal that contains two custom dropdown components, a text input, and a button. When the button is clicked, it filters data from an API. Currently, I am struggling to create a functional filter function despite multiple atte ...

Unable to add new Instance Properties in Vue.js within a Laravel project

I am attempting to develop a localization property similar to __('text') in Laravel blade template. I have set up a global window variable that contains all required data under the name window.i18n Below is my resourses/js/app.js file: require(& ...

Ways to extract particular pieces of data from complete JSON response API requests

I need assistance extracting only the Symbol and Company Name fields from a large JSON dataset while retrieving all data. How can I achieve this and then save the extracted information into a pandas DataFrame? Base_url Here is the code snippet: import re ...

Convert JSON strings with varying formats into objects of a uniform Java class

How can I deserialize JSON strings with different formats into instances of the same Java class using Jackson efficiently? Let's say I have information about users from various sources: Format 1: "user" : { "name" : "John", "age" : 21, ...

Concern with Isotope's masonry feature

I'm at my wit's end! The container div I'm dealing with is 1170px wide. My goal is to fit in 3 divs within this width. The first div is 275px wide, the second is 580px wide, and the third is also 275px wide. Altogether, these divs should ad ...