Search code examples
d3.jslabeltooltiplegendnvd3.js

NVD3: How to get values from tooltip or legend instead of labels?


  • The problem with using labels is that if a slice is too small the labels doesn't shows up and therefore, getting the value of label during onClick event fails

  • The problem is reproduced here http://plnkr.co/edit/3rCHWnxW7EFPXxWHLo96?p=preview. You will see that for Taxes the label is missing and therefore I can't get its value on click event enter image description here

what would be awesome?

  • If I can get the value from tooltip or legend instead of labels because labels are not a good idea to get values
  • Because I pass the value of label onclick to display other graph

enter image description here


Solution

  • In line 144-145 of your script.js, you can change this:

    .on('click', function(){
      var parentCategory = this.getElementsByClassName("nv-label")[0].textContent;
    

    to this:

    .on('click', function(d){
      var parentCategory = d.data.label;
    

    This way, you are passing in the __data__ of the clicked element to the click function, which you can access with d. This should solve your issue. You can also throw a console.log(d) within that function to see all the options available on the __data__ object.