如何在D3方向力布局图中为分类组添加颜色?

时间:2014-11-07 17:16:21

标签: d3.js colors nodes force-layout

我正在尝试将颜色填充应用于布局中的圆形节点。问题是我的节点在两组中加倍。在一组中,节点正确链接但颜色相同,在另一组中节点正确着色但未链接。 http://jsfiddle.net/akszila/yodwt3bm/

 // Compute the distinct nodes from the links.

links.forEach(function(link) {
        link.source = nodes[link.source] || (nodes[link.source] = {name: link.source, group: link.group});
      link.target = nodes[link.target] || (nodes[link.target] = {name: link.target, group: link.group});
    });

var color = d3.scale.category10();

var width = 960,
    height = 500;

var force = d3.layout.force()
    .nodes(d3.values(nodes))
    .links(links)
    .size([width, height])
    .linkDistance(30)
    .charge(-100)
    .on("tick", tick)
    .start();

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

// Per-type markers, as they don't inherit styles.
svg.append("defs").selectAll("marker")
    .data(["oszt"])
    .enter().append("marker")
    .attr("id", function (d) {
    return d;
})
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 16)
    .attr("refY", -1.5)
    .attr("markerWidth", 6)
    .attr("markerHeight", 6)
    .attr("orient", "auto")
    .append("path")
    .attr("d", "M0,-5L10,0L0,5");

var path = svg.append("g").selectAll("path")
    .data(force.links())
    .enter().append("path")
    .attr("class", function (d) {
    return "link " + d.type;
})
    .attr("marker-end", function (d) {
    return "url(#" + d.type + ")";
});

var circle = svg.append("g").selectAll("circle")
    .data(force.nodes())
    .enter().append("circle")
    .attr("r", 7)
    .style("fill", function (d) {
    return color(d.group);
})
    .call(force.drag);



var text = svg.append("g").selectAll("text")
    .data(force.nodes())
    .enter().append("text")
    .attr("x", 8)
    .attr("y", ".31em")
    .text(function (d) {
    return d.name;
})
    .style("fill", function (d) {
    return color(d.group);
});




// Use elliptical arc path segments to doubly-encode directionality.
function tick() {
    path.attr("d", linkArc);
    circle.attr("transform", transform);
    text.attr("transform", transform);
}

function linkArc(d) {
    var dx = d.target.x - d.source.x,
        dy = d.target.y - d.source.y,
        dr = Math.sqrt(dx * dx + dy * dy);
    return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
}

function transform(d) {
    return "translate(" + d.x + "," + d.y + ")";
}

如果我修改     var force = d3.layout.force() .nodes(d3.values(nodes)) .links(links) .size([width, height]) .linkDistance(30) .charge(-100) .on("tick", tick) .start();

var force = d3.layout.force() .nodes(nodes) .links(links) .size([width, height]) .linkDistance(30) .charge(-100) .on("tick", tick) .start(); 结果是节点被正确着色但没有链接,幸运的是没有重复。

0 个答案:

没有答案