d3.js学习-联系力学图

这个做了一个小小的改变

json数据也在以上链接


 

var width=screen.width-100,
      height=screen.height-160;
//颜色尺度
var color = d3.scale.category20();
//
var force=d3.layout.force()
        .charge(-120)//节点间的电荷,负数表示排斥,正数表示吸引
	.linkDistance(60)//节点间的距离
	.size([width,height]);//节点图的大小

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

d3.json("force.json",function(error,graph){//请求一个json文件,回掉函数
	//回调函数包括两个参数,error以及返回的json数据,即返回的数据
	force.nodes(graph.nodes)
		.links(graph.links)
		.start();//开始
	//定义连接线
	var link=svg.selectAll(".link")
		.data(graph.links)
		.enter()
		.append("line")
		.attr("class","link");
	//定义节点
	var node=svg.selectAll(".node")
		.data(graph.nodes)
		.enter()
		.append("circle")
		.attr("class","node")
		.attr("r",function(d){
			return 5+d.group;//半径
	        })
		.style("fill",function(d){
			return color(d.group);//颜色
		})
		.call(force.drag);
		//鼠标悬停
		node.append("title")
			.text(function(d){
				return d.name;
			});
		force.on("tick", function() {
			link.attr("x1", function(d) { return d.source.x; })
			      .attr("y1", function(d) { return d.source.y; })
			      .attr("x2", function(d) { return d.target.x; })
			      .attr("y2", function(d) { return d.target.y; });
					
		node.attr("cx", function(d) { return d.x; })
        		.attr("cy", function(d) { return d.y; });
		});

});     

css

.node{
	stroke:#fff;
	stroke-width:1.5px;
}

.link{
	stroke:#999;
	stroke-opacity:.6;
	stroke-width:1;
}

posted @ 2015-01-20 15:46  valentine is me  阅读(766)  评论(0编辑  收藏  举报