D3系列第四弹——绘制气泡图

来源:互联网 发布:surface软件推荐 编辑:程序博客网 时间:2024/05/21 15:07

不知道怎么说,只知道怎么写。先发出来,以后在仔仔细细的重构文章吧。

数据集:

{"children":[{ "name": "D3.js", "weight": 100 },{ "name": "Echarts.js", "weight": 77 },{ "name": "JavaScript", "weight": 70 },{ "name": "C/C++", "weight": 66 },{ "name": "Java", "weight": 66 },{ "name": "PHP", "weight": 56 },{ "name": "Ruby", "weight": 69 },{ "name": "Python", "weight": 73 },{ "name": "Windows", "weight": 44 },{ "name": "Linux", "weight": 90 },{ "name": "Unix", "weight": 85 },{ "name": "JSON", "weight": 40 },{ "name": "XML", "weight": 20 },{ "name": "JQuery", "weight": 44 },{ "name": "AngularJS", "weight": 44 },{ "name": "ajax", "weight": 20 },{ "name": "Node.js", "weight": 78 },{ "name": "Go", "weight": 54 },{ "name": "Swift", "weight": 24 },{ "name": "HTTP", "weight": 8 },{ "name": "Android", "weight": 14 },{ "name": "iOS", "weight": 10 }]}



HTML文件程序:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>D3Study</title>    <script type="text/javascript"src="D3/d3.min.js"></script>    <style>          .bubble circle{            stroke: black;            stroke-width: 2px;        }        .bubble text{            fill: black;            font-size: 14px;            font-family: arial;            text-anchor: middle;        }    </style></head><body><div id="bubble" style="height: 400px;background-color:#a9fdff"></div></body><script type="text/javascript" src="D3/Bubble.js"></script></html>


JS文件程序:

var width  = 400;var height = 400;var svg3 = d3.select("#bubble")    .append("svg")    .attr("width", width)    .attr("height", height);var pack = d3.layout.pack()    .size([ width, height ])    .sort(null)    .value(function(d){        return d.weight;    })    .padding(2);d3.json("Data/BubbleData.json",function(error, root){    var nodes = pack.nodes(root);    console.log(nodes);    var color = d3.scale.category20c();    var bubbles = svg3.selectAll(".bubble")        .data(nodes.filter(function(d) {            return !d.children;        }))        .enter()        .append("g")        .attr("class","bubble");    bubbles.append("circle")        .style("fill",function(d,i){            return color(i);        })        .attr("cx",function(d){ return d.x; })        .attr("cy",function(d){ return d.y; })        .attr("r",function(d){ return d.r; });    bubbles.append("text")        .attr("x",function(d){ return d.x; })        .attr("y",function(d){ return d.y; })        .text(function(d){            return d.name;        });});


最终效果: