Search code examples
angularjsd3.jsangular-nvd3

angular-nvd3 content percentage in tooltip


I am looking into ways I can display the percent of a slice of pie compared to the current graph in the tooltip.

First I tried looking for something similar to chart.labelType: 'percent' but it looks like there is no such option.

What I am trying to do now is calculate the percentage inside chart.tooltip.contentGenerator according to documentation the function should be passed 5 arguments function (key, x, y, e, series) -> String however I am only receiving the first argument.

I am using angular 1.5.0, d3 3.5.16, nvd3 1.8.2, and angular-nvd3 1.0.5.

What is the best practice for displaying the percentage in the tooltip?


Solution

  • EDIT: You brought up a great point that I didn't account for, that the total (and thus the percentage portion of each pie segment) will change when you remove segments from the pie. Looked into how to account for this, and I discovered you can monitor the chart for a stateChange, and configure what happens when this event is dispatched.

    So, what I've done is to update the total when that event is fired by filtering out whatever values are disabled:

    chart: {
      ...,
      dispatch: {
        stateChange: function(e) { 
          total = _.reduce(_.filter($scope.data, function(value) {
            return !value.disabled;
          }), function(result, value, key) {
            return result += parseFloat(value.y);
          }, 0);
          console.log(total);
        }
      },...
    };
    

    I've updated the example pie chart plunker with the new code, but everything else remained the same, except that I added in each key and the updated total into the tooltip so you can verify that it's working. But you'll still initialize the total value when the chart first loads:

    var total = _.reduce($scope.data, function(result, value, key) {
      return result += parseFloat(value.y);
    }, 0);
    

    ...And use the chart.tooltip.contentGenerator method to customize the tooltip message, which you can set up to return something like this:

    tooltip: {
      contentGenerator: function (key, x, y, e, series) {
        return '<h4>' + ((key.data.y / total) * 100).toFixed(2) + '% of total</h4>';
      }
    }
    

    Hope that helps!