Developing a dynamic horizontal bar chart in d3 using a multidimensional array or nested JSON dataset

I am in the process of creating a straightforward d3 bar chart () by utilizing this specific nested json file.

 {
 "clustername": "cluster1",
 "children": [
 {
 "neighborhoodname": "Shaw",
 "children": [
    {

    "totpop2000": "1005",
    "children": [
    {
        "name": "demographic",
        "children": [
        {"name": "Black", "size2000":0.18},
        {"name": "White", "size2000":0.6},
        {"name": "Hispanic", "size2000":0.40},
        {"name": "Asian", "size2000":0.10}
        ]
        },
    {
        "name": "wellbeing",
        "children": [
        {"name": "Unemployment", "size2000":0.40},
        {"name": "Poverty", "size2000":0.1},
        {"name": "Without HS Education", "size2000":0.31}
        ]
        },
    {
        "name": "crime",
        "children": [
        {"name": "Violent Crime", "size2000":0.09},
        {"name": "Property Crime", "size2000":0.08}
        ]
        },
    {
        "name": "housing",
        "children": [
        {"name": "Home Ownership", "size2000":0.34},
        {"name": "Houses for Rent", "size2000":0.50}
        ]
    }
   ]
   }
  ]
  }
 ]
}

In my JavaScript code, I have included the following logic to integrate the values marked as size2000 into the svg. However, there seems to be an issue with appending the correct set of data from my JSON file (it currently only retrieves the initial array/"clustername": "cluster1").

var data = d3.json("data/test.json", function(json) {
console.log(json); 

   
var bar = chart2000.selectAll("g")
      .data(data)
    .enter().append("g")
      .attr("transform", function(d, i) { return "translate(0," + i * height + ")"; });

  bar.append("rect")
      .attr("width", function(d) { return x((d.size2000)*100); })
      .attr("height", height - 1);

  bar.append("text")
      .attr("x", function(d) { return x((d.size2000)*100) - 3; })
      .attr("y", height / 2)
      .attr("dy", ".35em")
      .text(function(d) { return (d.size2000)*100); });

});

Could someone provide guidance on how to maintain the json data structure and successfully append the size2000 values to an svg? Any help is greatly appreciated!

Answer №1

One of the key principles in creating visualizations with D3 is establishing a connection between data and elements within the DOM. It's important for this mapping to consider the hierarchical structure of both the data and the DOM nodes, although it's not mandatory. Therefore, if your data is organized into nested sets, the visualization should also reflect this nesting (such as displaying multiple bar charts divided by hierarchy). Conversely, if you prefer a flat bar chart, your data should be structured as a flat list of values.

While it's not a strict requirement, maintaining a flat data structure can simplify both implementation and DOM mapping. You could manually flatten the JSON data for the bar chart like so:

d3.json("data/test.json", function(json) {

    var barChartData = [];
    function addLeaves(node) {
        if (typeof node.children !== "undefined") { 
            node.children.forEach(addLeaves); 
        } else { 
            barChartData.push(node); 
        }
    }
    addLeaves(json);

    var bar = chart2000.selectAll("g")
              .data(barChartData)
    // ...
}

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 Python to iterate through various pages on an API and extracting specific data before printing it

Hey there! I'm new to programming and practicing my skills. I've been exploring the Star Wars API, which contains data on characters, films, planets, and more from the Star Wars universe. Right now, I'm working on looping through all the pag ...

Error Arises When React Components Are Nested within Objects

I'm encountering a peculiar issue with my component. It works perfectly fine when retrieving data from State at a high level, but as soon as I try to access nested objects, it throws an error: "TypeError: Cannot read property 'name' of undef ...

What is the best method for displaying the accurate calculated value based on an element?

Within my "ROI calculator," there is a feature that allows users to adjust different labels. One of these labels is called "onlineRevenue." The concept is to recommend the most suitable plan based on the user's online revenue. However, I have some re ...

Leveraging the power of Firebase and JavaScript to easily include custom user fields during the user

UPDATE: I encountered an issue while using Nextjs framework. However, it works perfectly fine when I use a vanilla CRA (Create React App). It appears that the problem is somehow related to Nextjs. I'm currently working on creating a new user document ...

Having trouble loading a JSON file in three.js?

I have been trying to load a JSON image in Three.js by following a tutorial video. However, despite copying the code exactly as shown in the video, I am not able to see anything in the browser when using my own images. The JSON file is downloaded from clar ...

Capture cached images stored in the browser memory without relying on the source attribute of the <img> tag

Imagine you're managing a website, samplewebsite.com and you find that the images on it have been resized to very low quality. When you click on an image, you are directed to a 'view_image' page, for example samplewebsite.com/view?image=u ...

Attempting to access a non-object property - JSON parsing

I'm encountering an issue with consuming an API. Within the response, there is an array field called authors, and each author contains 2 fields. https://i.sstatic.net/1a5Fw.png I am trying to manage the text field but facing some errors. Here is ho ...

Having trouble with React button conditional rendering not functioning properly

Currently, I am working on a cart application and facing an issue. The problem is that the button is not getting disabled when the quantity reaches zero. Instead, it continues to show the 'add to cart' button even when no items are left in stock. ...

What could be causing the returned promise value to not refresh?

I am currently facing an issue with my program. Upon clicking a button, the goal is to update the "likes" attribute of a MongoDB document that has been randomly fetched. Despite setting up the logic for this, the update does not occur as intended: MongoCli ...

Ways to show text in a password field

I'm looking to have the password field on a page. I'd like to show the text "Enter password" on the screen before the user starts entering their password, but once they focus on the field to enter their password, it should switch back to password ...

"Enhance Your Website with jQuery Mobile's Multi-Page Setup and Panel

I am currently facing the challenge of managing multiple pages within a single document and I would like to utilize jQM 1.3's Panel widget to control navigation between these pages. However, the issue arises from the requirement that Panels must be co ...

The argument labeled as 'State' cannot be assigned to a parameter labeled as 'never'

I've recently delved into using TypeScript with React. I attempted to incorporate it with the React useReducer hook, but I hit a roadblock due to an unusual error. Below is my code snippet: export interface ContractObj { company: string; ...

Encountering a problem with scrolling the modal to the top

I am currently working on a code snippet that involves scrolling the modal to the top position. The purpose of this is to display form validation messages within the modal popup. Below are the jQuery code snippets that I have attempted: //Click event t ...

Is there a way to dynamically assign column names during the import process?

In my current scenario, I am importing data from various sources into my JSON backend. The mapping file will resemble the sample below. The question is how can I efficiently utilize this mapping during data import into my backend. The idea is to provide t ...

Ways to display distinct text boxes based on selected radio button?

Currently, I am working with JSP and have implemented an HTML form that includes a "Process" button at the top. When this button is clicked, it displays a form with two radio buttons - TestClient and TestServer. The form also contains a Submit button. If ...

The array becomes empty after a value has been assigned to it

I am currently working with a variable containing JSON data. var blogData = [ { "blogTitle":"Bangladesh", "imagePath":"/img/blog/bangladesh.jpg" },{ "blogTitle":"In ...

Jenkins is experiencing issues with starting up or reconnecting - It is hanging and displaying a severe error message: unable to properly read the JSON file provided at [/var/lib/jenkins/cb-envelope/envelope.json]

Jenkins: Version 2.89.4-x rolling Encountered slow performance issues with Jenkins due to memory problems. After trying to restart Jenkins using the sudo or usual method, a severe issue was encountered. Eventually, restarted the entire Jenkins machine in ...

What is the best way to get rid of a connect-flash notification?

I'm having trouble removing the message (with the username displayed) after logging out by pressing the logout button. Every time I try to press the logout button, it just refreshes the page without any action. I want to stay on the same page and not ...

The Ultimate Guide for Formatting JSON Data from Firebase

I'm facing an issue with parsing JSON data returned by Firebase. Here is the JSON snippet: { "-JxJZRHk8_azx0aG0WDk": { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cda6a68daaa0aca4a1e3aea2a0">[email&# ...

Unable to receive a response in React-Native after sending a post request

My current challenge involves sending a response back after successfully making a post request in react-native. Unfortunately, the response is not arriving as expected. router.route("/addUser").post((req, res) => { let name= req.body.name; connection ...