javascriptplottable

Conditional removal of label from Javascript Plottable Piechart


I have the following code:

window.onload = function(){
  var store = [{ Name:"Item 1", Total:18 },
               { Name:"Item 2", Total:7 },
               { Name:"Item 3", Total:3},
               { Name:"Item 4", Total:12}];
  

  var colorScale = new Plottable.Scales.Color();
  var legend = new Plottable.Components.Legend(colorScale);

  var pie = new Plottable.Plots.Pie()
  .attr("fill", function(d){ return d.Name; }, colorScale)
  .addDataset(new Plottable.Dataset(store))
  .sectorValue(function(d){ return d.Total; } )
  .labelsEnabled(true);

    
  new Plottable.Components.Table([[pie, legend]]).renderTo("#chart");
    
     
}
<link href="https://rawgithub.com/palantir/plottable/develop/plottable.css" rel="stylesheet"/>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://rawgithub.com/palantir/plottable/develop/plottable.js"></script>
<div id="container">
  <svg id="chart" width="350" height="350"></svg>
</div>

My question is how can I make the pie chart display only the labels with value greater or equal to 10 (i.e. a user defined limit)?


Solution

  • You can use labelFormatter in your case to conditionally hide the label.

    Use below code to hide label which are lower then 10.

    .labelFormatter(
        function(n)
        { 
          return parseInt(n) > 10 ? n.toString() : '';
        }
      );
    

    Note : The return type must be string in this case. That's why i used .toString().

    Here is the code

      var store = [{ Name:"Item 1", Total:18 },
                   { Name:"Item 2", Total:7 },
                   { Name:"Item 3", Total:3},
                   { Name:"Item 4", Total:12}];
      
    
      var colorScale = new Plottable.Scales.Color();
      var legend = new Plottable.Components.Legend(colorScale);
    
      var pie = new Plottable.Plots.Pie()
      .attr("fill", function(d){ return d.Name; }, colorScale)
      .addDataset(new Plottable.Dataset(store))
      .sectorValue(function(d){ return d.Total; } )
      .labelsEnabled(true)
      .labelFormatter(
        function(n)
        { 
          return parseInt(n) > 10 ? n.toString() : '';
        }
      );
        
      new Plottable.Components.Table([[pie, legend]]).renderTo("#chart");
    <link href="https://rawgithub.com/palantir/plottable/develop/plottable.css" rel="stylesheet"/>
    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script src="http://rawgithub.com/palantir/plottable/develop/plottable.js"></script>
    <div id="container">
      <svg id="chart" width="350" height="350"></svg>
    </div>