gpt4 book ai didi

javascript - 如何使用 Plottable.js 创建饼图

转载 作者:行者123 更新时间:2023-11-29 18:03:31 27 4
gpt4 key购买 nike

我尝试使用 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>

关于javascript - 如何使用 Plottable.js 创建饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33164488/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com