level 3
var body = d3.select("body");
var width = 620;
var height =620
var padding = { left:50, right:100, top:30, bottom:30 }
var svg = body.append("svg")
.attr("width", width)
.attr("height", height)
// 1.确定初始数据
var dataset = [
["财政扶贫资金",2500],["行业扶贫资金",1200],["社会帮扶资金",800],["信贷扶贫资金",600],["群众自筹资金",550],
["其它资金",600]
];
//2.转换数据
var pie = d3.layout.pie()
.value(function(d){
return d[1];
});
var piedata = pie(dataset);
console.log(piedata);
//绘图
var innerRadius =width/8; //内半径(绘制空心圆)
var outerRadius = width/4; //外半径
//创建弧生器
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
//随机产生颜色
var color = d3.scale.category20();
//drag
var drag = d3.behavior.drag()
.origin(function(d){return d;})
.on("drag", dragmove);
var arcs = svg.selectAll("g")
.data(piedata)
.enter()
.append("g")
.attr("class","g")
.each(function(d){ //指定当前的区域的平移量
d.dx=0;
d.dy=0;
})
.call(drag)
.attr("transform","translate("+( width/2 )+","+ ( height/2 ) +")");
//绘制弧
arcs.append("path")
.attr("fill",function(d,i){
return color(i); //设置弧的颜色
})
.attr("d", function(d){
return arc(d); //使用弧生器
})
.on("mouseover",function(d){
d3.select(this)
.style("opacity",0.6);
})
.on("mouseout",function(d){
d3.select(this)
.transition()
.duration(10)
.style("opacity",1.0);
});
//绘制弧内文字
arcs.append("text")
.attr("class","MyText")
.attr("transform", function(d){
var center = arc.centroid(d);
return "translate(" +
center[0] + "," +
center[1] + ")";
})
.text(function(d){
//计算资金总额百分比
var percent = Number(d.value)/d3.sum(dataset,function(d){return d[1];})*100;
//保留一位小数,末尾加上%返回。
return percent.toFixed(1) + "%";
});
//添加连接弧外文字的直线元素
arcs.append("line")
.attr("stroke","black")
.attr("x1",function(d){ return arc.centroid(d)[0] *1.34; })
.attr("y1",function(d){ return arc.centroid(d)[1] *1.34;})
.attr("x2",function(d){ return arc.centroid(d)[0] * 1.6; })
.attr("y2",function(d){ return arc.centroid(d)[1] *1.6; });
//添加弧外的文字元素
arcs.append("text")
.attr("transform",function(d){
var x = arc.centroid(d)[0] * 1.8;
var y = arc.centroid(d)[1] * 1.8;
return "translate(" + x + "," + y + ")";
})
.attr("text-anchor","middle")
.text(function(d){
return d.data[0];
});
//4. 交互式
function dragmove(d) {
d.dx += d3.event.dx;
d.dy += d3.event.dy;
d3.select(this)
.attr("transform","translate("+d.dx+","+d.dy+")");
}
//提示框
var tooltip = d3.select("body")
.append("div")
.attr("class","tooltip")
.style("opacity",0.0);
arcs.on("mouseover",function(d){
tooltip.html(d.data[0]+"的资金总额是:"+"<br/>"+ d.data[1] + "元")
.style("left",(d3.event.pageX) +"px")
.style("top",(d3.event.pageY+20 )+"px")
.style("opacity",1.0);
})
.on("mousemove",function(d){
tooltip.style("left",(d3.event.pageX)+"px")
.style("top",(d3.event.pageY+20 )+"px");
})
.on("mouseout",function(d){
tooltip.style("opacity",0.0);
});
2016年05月30日 13点05分


