1
我想要一個版本的我的力指向圖,它利用正方形而不是每個節點的圓圈。我用它來做的代碼工作正常,但不是以正方形爲中心,而是用左上角繪製每個正方形,圓形的中心位於圓形節點中。這意味着我的文字標籤不再居中。如何調整矩形對象的x和y位置以佔據與圓相同的空間?在力指向圖中調整節點位置
我用於圓形和方形節點的代碼如下。
function nearest(value, min, max, steps) {
var zerone = Math.round((value - min) * steps/(max - min))/steps; // bring to 0-1 range
return zerone * (max - min) + min;
}
force
.nodes(json.nodes)
.links(json.links)
.start();
var link = svg.selectAll(".link")
.data(json.links)
.enter().append("line")
.attr("class", "link")
.attr('stroke', function(d) {return d.color; })
.attr('stroke-width', 1)
.on("mouseover", function(d) {
d3.select(this).attr('stroke-width', 2);
})
.on("mouseout", function(d) {
d3.select(this).attr('stroke-width',1);
});
var node = svg.selectAll(".node")
.data(json.nodes)
.enter().append("g")
.attr("class", "node")
.call(force.drag);
node.append("circle")
.attr("r", function (d) nearest((Math.log(d.weight) *10), 10, 50, 5) || 10;})
.style('fill', function(d) { return d.color; })
.on("mouseover", function(d) {
link.style('stroke-width', function(l) {
if (d === l.target || d === l.source)
return 2;
})
link.style('stroke', function(l) {
if (d === l.target || d === l.source)
return 'aqua';
})
.duration(150);
})
.on("mouseout", function(d) {
link.style('stroke-width', 1)
link.style('stroke', function(d) {return d.color; })
.duration(150);
});
node.append("rect")
.attr("width", function (d) {return nearest(((Math.log(d.weight) *10)), 10, 50, 5) * 2 || 10;})
.attr("height", function (d) {return nearest(((Math.log(d.weight) *10)), 10, 50, 5) * 2 || 10;})
.style('fill', function(d) { return d.color; })
.on("mouseover", function(d) {
link.style('stroke-width', function(l) {
if (d === l.target || d === l.source)
return 2;
})
link.style('stroke', function(l) {
if (d === l.target || d === l.source)
return 'aqua';
})
.duration(150);
})
.on("mouseout", function(d) {
link.style('stroke-width', 1)
link.style('stroke', function(d) {return d.color; })
.duration(150);
});
這做到了!謝謝 - 我正在嘗試在轉換中的其他地方執行此操作,並只讓我的鏈接移動。 – medievalmatt