如何使用Plottable.js创建饼图

时间:2015-10-16 07:09:46

标签: javascript charts plottable plottable.js

我尝试使用Plottable.js创建一个饼图。 有谁知道怎么样?我对如何传递值并放入标签感到困惑。

以下是我的示例数据:

var store = [{ Name:"Item 1", Total:18 },
             { Name:"Item 2", Total:7 },
             { Name:"Item 3", Total:3},
             { Name:"Item 4", Total:12}];

再次感谢!

1 个答案:

答案 0 :(得分:4)

您可以使用Pie.sectorValue指定每个切片的值,然后可以使用Pie.labelsEnabled打开标签,该标签显示每个扇区的相应值。 您还可以使用Pie.labelFormatter

格式化标签

但是,我认为没有办法将扇区值以外的数据显示为标签,但根据您的需要,图例可能会有效

以下是带图例的饼图示例:

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)
  .labelFormatter(function(n){ return "$ " + n ;});
    
  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>

或者,如果所有值都是唯一的,那么您可以使用labelFormatter

来破解它

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 reverseMap = {};
  store.forEach(function(s) { reverseMap[s.Total] = s.Name;});
    
  var ds = new Plottable.Dataset(store);  
  

  var pie = new Plottable.Plots.Pie()
  .addDataset(ds)
  .sectorValue(function(d){ return d.Total; } )
  .labelsEnabled(true)
  .labelFormatter(function(n){ return reverseMap[n] ;})
  .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>