【d3.js教程09】包图pack

【d3.js教程09】包图pack_第1张图片

<!DOCTYPE html>
<html>
	<head>
		<script src="js/d3.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/jquery-1.11.3.min.js" type="text/javascript" charset="utf-8"></script>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			text{
				font-size: 4px;
			}
		</style>
	</head>
	<body>
		<svg></svg>
		<script type="text/javascript">
			var width =300;
			var height =300;
			var svg = d3.select("svg");
				svg.attr("width",1000)
					.attr("height",1000)
					.attr("x",100)
					.attr("y",100);
			/*初始化包布局*/
			var pack = d3.layout.pack()
	    			.size([ width, height])
	    			.radius(10);
			d3.json("json/jiqun.json", function(error, root) {
				var nodes = pack.nodes(root);
				var links = pack.links(nodes);
					/*添加小球*/
					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,i){
							d3.select(this)
								.attr("fill","yellow");
						})
						.on("mouseout",function(d,i){
							d3.select(this)
							.attr("fill","rgb(31, 119, 180)");
						});
					/*添加文字*/
					svg.selectAll("text")
						.data(nodes)
						.enter()
						.append("text")
						.attr("dx",function(d){
							return d.x-6;
						})
						.attr("dy",function(d){
							return d.y+2;
						})
						.text(function(d,i){
							return d.name;
						})
						.style("fill",function(d){
							return d.children?"blue":"white";
						});
			})
		
	</script>
	</body>
</html>


你可能感兴趣的:(d3,d3.js,包图,d3.js教程,d3入门)