2015-12-02 60 views
0

我有以下代碼:條件移除標籤從Javascript Plottable餅圖

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>

我的問題是如何使餅圖顯示只值大於或等於標籤10(即用戶定義的限制)?

回答

1

您可以在您的案例中使用labelFormatter來有條件地隱藏標籤。下面的代碼

使用隱藏的標籤,它們是低級然後10

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

注:返回類型必須是在這種情況下字符串。這就是爲什麼我使用.toString()。

下面是代碼

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>