如何使用Plottable.js创建饼状图

How to create Pie chart using Plottable.js

本文关键字:创建 js 何使用 Plottable      更新时间:2023-09-26

我尝试使用Plottable.js创建一个饼状图。有人知道怎么做吗?我对如何传递值和放置标签感到困惑。

下面是我的示例数据:

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

再次感谢!

您可以使用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>