Tips for dynamically updating data with on.click functions in D3

Implementing pack layout with D3 v4 is my current task, and I am looking to adjust the circle sizes based on the values "funds" and "spend" in my csv file.

The following code successfully scales the circles:

rank(funds)
rank(spend)

However, the on.click events are not functioning to scale the circles:

d3.select("#funds")
 .on("click", function () {
   return rank(funds);
});

For the code and data, here is the link to the plunker:

https://plnkr.co/edit/vp3MuQZEU85cNI1KUlc5?p=info

var diameter = 400

var color = d3.scaleOrdinal()
    .range(["#ff433d", "#ff8e8b", "#ffc6c4", "#5c42ab", "#9d8ecd", "#cec6e6"])

var pack = d3.pack()
  .size([diameter, diameter])
  .padding(1.5)

var vis = d3.select("#svgid").append("svg")
  .attr("width", diameter)
  .attr("height", diameter)
  .attr("class", "pack")
  .append("g");

//DRAW CHART

d3.csv("bil-rupeex.csv", function(data) {

  var root = { name: "decade", children: data };
    
//UPDATE DATA

    funds = d3.hierarchy(root)
      .sum(function(d) { return d.funds })
      
    spend = d3.hierarchy(root)
      .sum(function(d) { return d.spend })

    function rank(data) {    
    
    pack(data);

    var node = vis.selectAll("circle")
      .data(data.descendants())
      .enter().append("circle")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
      .attr("r", function(d) { return d.r; })
      .attr("fill", function(d) {
        return color(d.data.scam);
      })
   
    node.exit().remove();

  }
 
  rank(funds);
  

//BUTTONS

  d3.select("#funds")
    .on("click", function () {
      return rank(funds);
    });

  d3.select("#spend")
    .on("click", function () {
      return rank(spend);
    });

  
})

Answer №1

Make sure to eliminate all circles within your click handler and actually execute the rank function, rather than merely returning a reference to it.

var diameter = 400

var color = d3.scaleOrdinal()
    .range(["#ff433d", "#ff8e8b", "#ffc6c4", "#5c42ab", "#9d8ecd", "#cec6e6"])

var pack = d3.pack()
  .size([diameter, diameter])
  .padding(1.5)

var vis = d3.select("#svgid").append("svg")
  .attr("width", diameter)
  .attr("height", diameter)
  .attr("class", "pack")
  .append("g");

//DRAW CHART

d3.csv("bil-rupeex.csv", function(data) {

  var root = { name: "decade", children: data };

//UPDATE DATA

    funds = d3.hierarchy(root)
      .sum(function(d) { return d.funds })

    spend = d3.hierarchy(root)
      .sum(function(d) { return d.spend })

    function rank(data2) {    

    pack(data2);

    var node = vis.selectAll("circle")
      .data(data2.descendants())
      .enter().append("circle")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
      .attr("r", function(d) { return d.r; })
      .attr("fill", function(d) {
        return color(d.data.scam);
      })

    node.exit().remove();

  }

  rank(funds);
  rank(spend);


//BUTTONS

  d3.select("#funds")
    .on("click", function () {

      vis.selectAll("circle").remove()


       rank(funds);
       console.log("funds")

    });

  d3.select("#spend")
    .on("click", function () {

      vis.selectAll("circle").remove()
      rank(spend); 


    });


})

Forked plunkr: https://plnkr.co/edit/ky23JGZciJAA4LUK12If?p=preview

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

Angular Directives in Error

Help needed with creating a custom directive in Angular. Seeking guidance :) I am trying to display the content from 'directive.html' within the 'app-info' directive. The code functions properly without the directive, indicating a mist ...

What is the best way to arrange this by DateTransaction using a dropdown list?

Requesting assistance from the PHP community! I'm a newbie and in need of your expertise. My task is to create a dropdown list that sorts a table based on the DateTransaction column, with options ranging from January to December. Here is the code sni ...

In Javascript, you can throw, instantiate a new Error(), and populate its custom properties all in a single line of code

Can all of this be done in a single line? if (!user) { const error = new Error('Invalid user.') error.data = someObject error.code = 401 throw error } Here's an example (with data and code properties populated) if (!user) th ...

Changing a callback function into a promise in Node.js for OpenTok integration

MY FUNCTIONAL CODE (SUCCESSFULLY WORKING!) I have developed a function with callback to generate tokens and create sessions for OpenTok. This function is then exported to the application. The function //Dependencies var opentok = require('./ot&ap ...

Looking for assistance in establishing a connection between Node.js and Angular.js

I have a decent understanding of mongodb and node.js, but I'm struggling with angular.js. I need some help in figuring out how to retrieve data from my node.js code using angular.js. If there are any errors in my node.js code, please let me know. var ...

When trying to access the page via file://, the cookies are not functioning properly

My HTML code is functioning properly in Firefox and even on the W3Schools website when tested using their editor in Chrome. However, when I run my code in Chrome from Notepad++, it doesn't seem to work. It appears that the body onload event is not tri ...

Unable to retrieve responseText from AJAX call using XrayWrapper

I am utilizing the IUI framework and attempting to retrieve the results from an ajax call. When inspecting the call in Firebug, it shows an "XrayWrapper[Object XMLHttpRequest{}", but I am struggling to access the responseText from the object. Upon expand ...

Executing jQuery AJAX with PHP using 'POST' method to receive and process PHP code

Something seems to have gone wrong with my setup; it was functioning properly before but is now encountering issues. When trying to make a POST call from an HTML file to a php file (which fetches data from a REST API), instead of receiving the expected API ...

Background image fixed with scrolling effect

I've been struggling with a parallax effect on my website. After seeing it work smoothly on other websites, I tried to implement it myself but couldn't quite get it right. The background image keeps moving when I scroll the page and I want it to ...

Embracing right-to-left (RTL) languages

I am looking to create a website that can support both left-to-right (LTR) and right-to-left (RTL) languages seamlessly. My goal is to have the text direction switch automatically to RTL if the content is in an RTL language. Additionally, I want the input ...

When you find that the plugins on pub.dev do not offer web support, consider utilizing npm packages for Flutter web development

I am currently working on developing a cross-platform app using Flutter for iOS, Android, and web. However, some plugins do not support web. Fortunately, I came across npm packages that provide the same functionality and I am considering integrating them. ...

Modifying properties within child components

Within my parent Vue Page, I have inserted a FormInput component inside my form. new.vue <b-form @submit.prevent="submit"> <FormInput :name="name"/> <b-button @click="submit">Save</b-button> <b-form> <script> i ...

Tips for showcasing a designated set of numbers in Vue Js while iterating?

Is there a way to specifically target numbers during a loop? For example, I only want to retrieve numbers 5 and above or within a certain range that I specify. <select name="" id="input" class="form-control" v-model="selectcompetitionyear"> < ...

Ways to conceal a parameter in Angularjs while functioning within the ng-bind directive

I am using Angular to create the final URL by inputting offer information. Below is the code snippet: <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> ...

What is the reason behind JSLint's preference for x === "undefined" over typeof x == "undefined"?

I'm feeling lost when it comes to JSLint. Initially, my code checked if div:jqmData("me") was undefined in this way: if ( typeof el.jqmData("me") == "undefined" ? el.not(':jqmData(panel="main")').length > 0 : el.not(':jqm ...

Retrieve the radio button value from the HTML form

This website is designed to calculate ideal weight based on input data, but I am encountering an issue with the gender selection. The code seems to only recognize the first condition for female, while ignoring the else if condition for male. How can I fix ...

Performing a function multiple times by clicking the mouse

I have a function called week(), which provides me with the current first (startDate) and last (endDate) day of the week along with the week number. Additionally, there are two other functions, namely weekPlus() and weekMinus(), containing variables that i ...

jqGrid display/hide columns options dialogue box

I am looking to implement a feature that allows users to toggle columns in my jqGrid. I came across a module for this purpose, but unfortunately, it is no longer supported in jqGrid 4.x. I have searched for a replacement module without success. Are there ...

Tips for exploring electron without launching additional windows

Is there a way to navigate between HTML pages within the same window without opening multiple windows in Electron? ...

The 'checked' property cannot be bound to 'mat-button-toggle' as it is not recognized as a valid property in Angular 9

I am encountering an issue with my Angular 9 application. I have integrated angular-material and imported the MatCheckboxModule correctly in the module. Here is the version of the material package I am using: "@angular/material": "^10.2.0&q ...