d3力导向图增加节点_为D3力导向的布局节点设置不同的图像

bd96500e110b49cbb3cd949968f18be7.png

I've been trying to make a specific type of force direct graph, similar to this (http://bl.ocks.org/mbostock/950642):

B7oVS.jpg

However, instead of having all the same images I wish to have different images representing different information on the graph.

My first step to this is being able to change all the circle images to random linked shapes. Whatever I try to implement in my code, the circles I have just disappear, instead of being replaced by different shapes. Any help on this problem would be great. Here is the code. Sorry, I'm also new to this site.

// nodes

var nodeSelecton = svg.selectAll(".node").data(nodes).enter().append("g").attr({

class : "node"

}).call(force.drag);

nodeSelecton.append("circle").attr({

r : nodeRadius

}).style("fill", function(d) {

return color(d.group);

});

nodeSelecton.append("svg:text").attr("text-anchor", "middle").attr('dy', ".35em").text(function(d) {

return d.name;

});

// Add a new random shape.

// nodes.push({

// type: d3.svg.symbolTypes[~~(Math.random() * d3.svg.symbolTypes.length)],

// size: Math.random() * 300 + 100

解决方案

This is a jsfiddle that is exuivalent to the first example that you linked. I juist changed getting data to be from the JavaScript code instead of json file, since jsfiddle doesn't support external json files that well.

First Solution

Now, let's replace constant image with set of different images

Instead of this code:

.attr("xlink:href", "https://github.com/favicon.ico")

we'll insert this code:

.attr("xlink:href", function(d) {

var rnd = Math.floor(Math.random() * 64 + 1);

var imagePath =

"http://www.bigbiz.com/bigbiz/icons/ultimate/Comic/Comic"

+ rnd.toString() + ".gif";

console.Log(imagePath);

return imagePath;

})

and we'll get this:

SJRVP.png

Second Solution

As you suggested in your code from the question, one could use built-in SVG symbols.

Instead of this whole segment for inserting images:

node.append("image")

.attr("xlink:href", "https://github.com/favicon.ico")

.attr("x", -8)

.attr("y", -8)

.attr("width", 16)

.attr("height", 16);

we could use this code:

node.append("path")

.attr("d", d3.svg.symbol()

.size(function(d) {

return 100;

})

.type(function(d) {

return d3.svg.symbolTypes[~~(Math.random() * d3.svg.symbolTypes.length)];

}))

.style("fill", "steelblue")

.style("stroke", "white")

.style("stroke-width", "1.5px")

.call(force.drag);

and we'll get this:

6JPIA.png

Hope this helps.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值