d3.js——圆形分区图

var width = 600,
    height = 400,
    radius =  Math.min(width, height) / 2 ,
    color = d3.scale.category20();
var svg = d3.select("body").append("svg")
    .attr("width",width)
    .attr("height",height)
    .append("g")
    .attr("transform", "translate(" + radius + "," + radius + ")");

//定义分区图函数
var partition = d3.layout.partition()
    .sort(null)
    .size([Math.PI*2,radius*radius])
    .value(function (d) {
    return 1
})

//读取数据并绘制

d3.json("city.json", function (errror,root) {
    var nodes = partition.nodes(root),
        links = partition.links(nodes);


//绘制圆环

var arc = d3.svg.arc()
        .startAngle(function(d){return d.x})
        .endAngle(function (d) {return d.x + d.dx})
        .innerRadius(function (d) {return Math.sqrt(d.y)})
        .outerRadius(function(d){return Math.sqrt(d.y+ d.dy)})

  var arcs = svg.selectAll("g")
        .data(nodes)
        .enter()
        .append("g")
    arcs.append("path")
        .attr("display",function(d){return d.depth?null:"none"})
        .attr("d",arc)
        .style("stroke","#fff")
        .style("fill",function(d){return color ((d.children?d: d.parent
        ).name)})
        .on("mouseover", function (d) {
            d3.select(this)
                .style("fill","yellow")
        })
        .on("mouseout",function(d){
            d3.select(this)
                .transition()
                .duration(200)
                .style("fill", function (d) {
                    return color((d.children?d: d.parent).name)
                })
        })
    arcs.append("text")
        .attr("font-size","12px")
        .attr("font-family","simsun")
        .attr("txet-anchor","middle")
        .attr("transform",function(d,i){
            if(i == 0)
            return "translate("+arc.centroid(d)+")"
            var r = 0;
            if ((d.x+ d.dx/2)/Math.PI*180<180)
                r = 180 * ((d.x + d.dx / 2 - Math.PI / 2) / Math.PI);
            else
                r = 180 * ((d.x + d.dx / 2 + Math.PI / 2) / Math.PI);
            return  "translate(" + arc.centroid(d) + ")" +
                "rotate(" + r + ")";
        })
        .text(function(d) { return d.name; });



你可能感兴趣的:(圆形分区图)