Tôi đã tạo đồ thị có hướng lực với plugin d3.js và tôi muốn tô màu các nút và các nhãn có màu khác nhau theo nhóm mà chúng thuộc về.D3.js lực lượng đồ thị hướng, mỗi nhóm màu sắc khác nhau?
Tôi đã thêm quy mô cho màu:
var color = d3.scale.category20();
và đến nút biến Tôi đã thêm:
.style("fill", function(d) { return color(d.group); })
nhưng tất cả các nút trong cùng một màu sắc ..
đây là tình trạng hiện tại của tôi: http://jsfiddle.net/WBkw9/
toàn bộ tập lệnh:
var links = [
{source: "John", target: "Mike", group: "5"},
{source: "John", target: "Janice", group: "5"},
{source: "John", target: "Caleb", group: "5"},
{source: "John", target: "Anna", group: "4"},
{source: "John", target: "Tommy", group: "3"},
{source: "John", target: "Jack", group: "2"},
{source: "John", target: "Vilma", group: "1"},
];
var nodes = {};
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});
});
var color = d3.scale.category20();
var width = 960,
height = 500;
var force = d3.layout.force()
.nodes(d3.values(nodes))
.links(links)
.size([width, height])
.linkDistance(60)
.charge(-300)
.on("tick", tick)
.start();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var link = svg.selectAll(".link")
.data(force.links())
.enter().append("line")
.attr("class", "link");
var node = svg.selectAll(".node")
.data(force.nodes())
.enter().append("g")
.attr("class", "node")
.style("fill", function(d) { return color(d.group); })
.on("mouseover", mouseover)
.on("mouseout", mouseout)
.call(force.drag);
node.append("circle")
.attr("r", 8);
node.append("text")
.attr("x", 12)
.attr("dy", ".35em")
.text(function(d) { return d.name; });
function tick() {
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("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
}
function mouseover() {
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", 16);
}
function mouseout() {
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", 8);
}
Tôi thiếu gì cho các màu khác nhau trên mỗi nhóm?
điều này chỉ thay đổi màu theo cách đó để chỉ nút được tô màu và không phải toàn bộ văn bản. Nhưng điều này vẫn không giải quyết được vấn đề của tôi, http://jsfiddle.net/F2fbu/. Tôi muốn nhận được mọi nhóm màu khác nhau, bây giờ dường như với tôi rằng tôi không thể làm điều này với loại dữ liệu đó vì tôi cần xác định nhóm nào là nút nào ... – dzordz
Nhóm phải là một số nguyên chứ không phải là một chuỗi. 'd3.selectAll (" circle ") style (" fill ", function (d) {return color (9)})' thay đổi màu của tất cả các vòng tròn. – user4815162342