d3,圆弧 arc,饼图

  • Post author:
  • Post category:其他











代码:基本数据,[5,6,7]




var w=300;
var h=300;
var dataset=[5,6,7];

pie是饼图的函数




var pie=d3.layout.pie();

初始化svg

var svg=d3.select("body")
		.append("svg")
		.attr("width",w)
		.attr("height",h);
var outRadius=w/2;
var innerRadius=w/4;
var arc=d3.svg.arc()
		.innerRadius(innerRadius)
		.outerRadius(outRadius);
		
var arcs=svg.selectAll("g.arc") //生成和dataset对应的g ,class是arc,数据集有多少个,类有多少个
		.data(pie(dataset)) //pie(dataset)把数据本身进行改变
		.enter()
		.append("g")
		.attr("class","arc")
		.attr("transform","translate("+outRadius+","+innerRadius+")"); //圆心位置

color是d3自带的配色

var color=d3.scale.category10();

arcs.append(“path”)



.attr(“fill”,function(d,i){



return color(i);



})



.attr(“d”,arc);

结果生成了圆环图



以下 是浏览器生成的代码




<svg width="300" height="300">
<g class="arc" transform="translate(150,75)">
<path fill="#1f77b4" d="M-147.7211629518312,26.04722665003954A150,150 0 0,1 -2.7553642961003488e-14,-150L-1.3776821480501744e-14,-75A75,75 0 0,0 -73.8605814759156,13.02361332501977Z"></path></g>
<g class="arc" transform="translate(150,75)">
<path fill="#ff7f0e" d="M96.41814145298092,114.90666646784669A150,150 0 0,1 -147.7211629518312,26.04722665003954L-73.8605814759156,13.02361332501977A75,75 0 0,0 48.20907072649046,57.453333233923345Z"></path></g>
<g class="arc" transform="translate(150,75)">
<path fill="#2ca02c" d="M9.18454765366783e-15,-150A150,150 0 0,1 96.41814145298092,114.90666646784669L48.20907072649046,57.453333233923345A75,75 0 0,0 4.592273826833915e-15,-75Z"></path></g></svg>

pie(dataset)的数据

pie(dataset)
[
Object
data: 5
endAngle: 6.283185307179586
padAngle: 0
startAngle: 4.537856055185257
value: 5
__proto__: Object
, 
Object
data: 6
endAngle: 4.537856055185257
padAngle: 0
startAngle: 2.443460952792061
value: 6
__proto__: Object
, 
Object
data: 7
endAngle: 2.443460952792061
padAngle: 0
startAngle: 0
value: 7
__proto__: Object]



可以看到数据有padAngle,修改以下相应的参数,就有了




版权声明:本文为artemisrj原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。