Generating multiple d3.js charts on a single page using various sections of the same JSON dataset

I have been on a thorough search to find the issue in my code, but sadly I haven't been able to identify it. Please forgive me if there's something obvious that I'm missing.

The JSON object I am working with is structured like this:

var data={
    "by_date":[
        {"date":"2014-01-01", "count":10},
        {"date":"2014-02-01", "count":20},
        {"date":"2014-03-01", "count":30},
        {"date":"2014-04-01", "count":15},
        {"date":"2014-05-01", "count":20}
    ],
    "by_location": {
        "name":"World","children":[
            {
                "name":"United States", "children":[{"name":"New York", "children":[{"name":"Albany","count":5}, {"name":"NYC","count":5}]}]
            },
            {
                "name":"Canda", "children":[
                    {
                        "name":"Alberta", "children":[{"name":"Edmonton","count":5},{"name":"Calgary","count":5}]
                    },
                    {
                        "name":"British Columbia", "children":[{"name":"Victoria","count":2},{"name":"Vancouver","count":8}]
                    }
                ]
            },
            {
                "name":"China", "children":[{"name":"Beijing","count":30}]
            },
            {
                "name":"India", "children":[{"name":"Bangalore","count":15}]
            },
            {
                "name":"Germany", "children":[{"name":"Frankfurt","count":20}]
            }
        ]
    }
};

My goal is to showcase a line chart using data from data.by_date and a zoomable circlepack from data.by_location simultaneously on one HTML page. I have two Javascript functions, by_date, responsible for creating the line chart, and by_location, designed for generating the circlepack. Both these functions mirror Mike Bostock's line chart and zoomable circlepack examples. Here's how I call them:

by_date(data.by_date);
by_location(data.by_location); // Circlepack displays, but zoom feature doesn't work.

The issue arises when although both the line chart and the circlepack are successfully displayed on the page, the zoom functionality fails to function properly on the circlepack, triggering the following error:

Uncaught TypeError: Cannot read property 'parent' of undefined

Strangely, if I comment out the by_date call and only execute by_location, everything works seamlessly.

// by_date(data.by_date);
by_location(data.by_location); // Zoom feature now operates smoothly!

Given that by_date strictly utilizes data.by_date and does not interact with data.by_location at all, why would omitting it make by_location operate correctly?

Below are fiddles illustrating the problem:

Both the line chart and the circlepack (where zooming malfunctions): http://jsfiddle.net/xk5aqf8t/6/

With the line chart function by_date commented out (zoom feature works flawlessly): http://jsfiddle.net/38sayeqa/

Please note that the sole disparity between the two fiddles is the absence of the call to by_date.

Your assistance is immensely valued. Thank you in advance!

Answer №1

The issue in this scenario arises from the fact that your zoom transition is targeting all text elements across the entire document, including those within the line chart where the bound data lacks a parent property (leading to the error notification).

The solution is straightforward. Simply confine your transition selection to the current chart. Since you already have a selection of text elements in place, you can easily repurpose it as shown below:

// Preserve the initial selection in the variable 'text':
var text = svg.selectAll('text').data(nodes);
text.enter()... // keep the entering selection separate

// Initiate a new transition on the existing selection of text nodes
var transition = text.transition().duration(...); // the transition will make use of the original 'text' selection
transition.filter(...); // avoid subselecting any additional elements here

Check out this demo for reference.

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

Having trouble reading JSON file using Pandas

data=pd.read_json("https://api.covid19india.org/state_district_wise.json") data transposed_data = data.transpose() transposed_data I'm working on extracting districtData from this API but I'm facing difficulties. The column contains key-value p ...

The jQuery document.ready event fails to trigger when invoked after using ScriptManager.RegisterStartupScript in the code-behind

I am currently working with a filtered list of items utilizing a tool called Check out the screen for a visual example. In the user flow, after selecting to add another action, a fancybox popup is triggered displaying the next image: After the user adds ...

What is the significance of the NS_ERROR_UNKNOWN_PROTOCOL error code?

When attempting to make an AJAX request using Angular 1.5.9, my code is as follows: $http.get('localhost:8080/app/users').then(function(resp) { ... }); However, I am encountering an error that reads: "NS_ERROR_UNKNOWN_PROTOCOL" (...) stack: "c ...

Tacking the progress bar onto an array of $.ajax() calls within a Promise.all

FINAL UPDATE 25/06/20: After a thorough investigation, I discovered the root causes of why the progress bar was not functioning as intended. Firstly, dealing with $.ajax() proved to be cumbersome due to its lack of proper promise handling. To resolve this ...

Steps for differentiating parameters with identical names in JSON

I've come across numerous questions regarding String to JsonObject conversion, but I'm struggling to find a working solution. I'm currently using Java 17 and trying to retrieve data from an API where two values need to be split into separate ...

What is the method to make a file download using JavaScript?

In my jQuery ajax form, a user inputs their email and upon submission, they should receive an automatic download of a file. Here is the structure of the form: $(".email-form").submit(function(event) { event.preventDefault(); var $form = $(this), ...

Why is my grid not showing the elements properly in ReactJS and CSS?

Currently, I am working with ReactJS, GridCSS in the Gatsby framework. I am attempting to create a subgrid within a subcomponent of the Gatsby layout.js file. However, after setting up my grid, the subcomponent fails to display the component correctly in i ...

Resolving JSON/AJAX Problem Arising from Server Session Expiration

I've encountered a frustrating issue with my website where ajax and json calls are not working after the session timeout of 120 minutes on the server side. When a user attempts to make a call from a loaded page after the timeout, the call goes through ...

Achieving Equal Heights in Two Grid Sections using React MUI

How can I create two separate grids next to each other using MUI, both taking up 50% of a larger grid? In the image displayed below, I am struggling to make the heights of the two sections match. I want the smaller grid items (cards) to dynamically adjust ...

Using Promise.all within an async function to handle variables inside of Lambda functions

I've spent the past couple of days trying to find a solution to this issue. I've simplified my code to mostly pseudo code for ease of understanding. What I'm struggling with is creating an async function that acts as a trigger for an SQS qu ...

Converting multiple columns into JSON using MySQL

I'm looking to convert multiple columns from one table into a single JSON format in another table within my MySQL database (version 5.7.16) using an SQL query. The structure of the first table is as follows: CREATE TABLE `log_old` ( `id` INT(10) ...

Sign up for your own personalized Express and HBS helper now!

As a newcomer to Node, I appreciate your patience with me. I recently utilized the express generator module with the -hbs flag to switch from the default templating engine to Handlebars. Currently, I am attempting to register a custom helper to enable me ...

Jquery Magic: Perfectly Aligning Carousel Items

I am striving to replicate this specific layout using the items in the carousel: https://i.sstatic.net/XVOuT.png However, this is what I have managed to achieve so far: https://i.sstatic.net/5zrpx.png Here you can find my code along with a fiddle http:/ ...

Ever since updating from jQuery 1.4 to 1.5, there have been issues with data getting overridden

After updating to the most recent version of jQuery above 1.4, I noticed that my ajax posts are no longer accepting ?? (double question marks). Instead, they are being replaced with something like jQuery15206629880418804291_1302038490086 Using Firebug, I ...

Using Tinymce 4.1.9 with raw ajax instead of JQuery: A step-by-step guide

I am currently working with Tinymice 4.1.9 for textarea validation in a raw ajax environment as I have limited knowledge of jquery. The issue I'm facing is that when Tinymce 4.1.9 is added to the textarea, upon validation, I receive an empty string un ...

Timing measurements in JavaScript: comparing Date.now with process.hrtime

I need to regularly calculate the time difference between specific time intervals. When it comes to performance, which method is more efficient: Date.now or process.hrtime? C:\Windows\system32>node > process.hrtime() [ 70350, 524700467 ] ...

Challenge in backward compatibility when converting from .on() to .live()

Struggling to make hammer.js work with an outdated 1.6 jQuery in my CMS. The function "on()" isn't available, so I have to use "live()". Here are the two instances: 1. var hammertime = new Hammer(element[0], { drag_lock_to_axis: true }); hammertime. ...

Converting a Finsweet hack #4 from jQuery to pure JavaScript in Webflow: Step-by-step guide

I have a jQuery code that I need to convert to pure JavaScript. Can you assist me in translating this code into pure JavaScript? I have left comments in the code to make it easier. ORIGINAL JQUERY CODE: // When the DOM is ready document.addEventListener(& ...

Working with JSON object values in a Spring Boot application

Here is a sample JSON data: [{"state":"Completed","mignum":146289,"projectleader":"Eric Lok","productiondate":"Jun 6, 2018","installationtiers":"Windows Server","targetplatform":"Production","apprelated":"UPS Pickup Point Web Application","appversion":"2. ...

The buffer for the operation `users.insertOne()` exceeded the timeout limit of 10000 milliseconds, resulting in a Mongoose

I am currently utilizing a generator that can be found at this Github link Project repository: Github Project Link Encountering an issue when attempting to input a user using the `MASTER_KEY`, I keep receiving the following error message: MongooseError ...