d3.js——绘制打包图

打包图其实就是通过d3.layout.pack()进行数据转换后,然后画圈圈咯~~

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>打包图</title>
</head>
<body>
<script src="d3.js"></script>
<script src="js/pack.js"></script>
</body>
</html>

/**
 * Created by Silence_C on 2016/4/27.
 */
var width = 600,
    height = 600;

//定义数据转换函数
var pack = d3.layout.pack()
.size([width,height])
.radius(20);

var svg = d3.select("body").append("svg")
    .attr("width",width)
    .attr("height",height)

//取数据,绘图
d3.json("city2.json",function(error,root){
    var nodes = pack.nodes(root);
    var links = pack.links(nodes);

    console.log(nodes);
    console.log(links);

    //画圈圈
    svg.selectAll("circle")
        .data(nodes)
        .enter()
        .append("circle")
        .attr("fill","rgb(31,119,180)")
        .attr("fill-opacity","0.4")
        .attr("cx",function(d){return d.x})
        .attr("cy",function(d){return d.y})
        .attr("r", function (d){return d.r})
        .on("mouseover", function (d) {
            d3.select(this)
                .attr("fill","yellow")
        })
        .on("moouseout",function(d){
            d3.select(this)
                .attr("fill","rgb(31,119,180)")
        })

    //添加文字
        svg.selectAll("text")
            .data(nodes)
            .enter()
            .append("text")
            .attr("x",function(d){return d.x})
            .attr("y", function (d) {return d.y})
            .attr("font-size","10px")
            .attr("fill","white")
            .text(function(d){return d.name})



})

效果图如下:

d3.js——绘制打包图_第1张图片


你可能感兴趣的:(svg,数据转换,d3.js,打包图,d3.layout.pack)