D3 силовая направленная компоновка с ограничительной рамкой
Я новичок в D3 и не могу установить границы для моей силовой направленности. Мне удалось собрать воедино (из примеров) то, что я хотел бы, но мне нужно, чтобы график содержался. В тиковой функции transform / translate правильно отобразит мой график, но когда я использую cx и cy с Math.max/min (см. Комментарий к коду), узлы прикрепляются к верхнему левому углу, в то время как строки содержатся правильно.
Вот что у меня ниже... что я делаю не так??
var w=960, h=500, r=8, z = d3.scale.category20();
var color = d3.scale.category20();
var force = d3.layout.force()
.linkDistance( function(d) { return (d.value*180) } )
.linkStrength( function(d) { return (1/(1+d.value)) } )
.charge(-1000)
//.gravity(.08)
.size([w, h]);
var vis = d3.select("#chart").append("svg:svg")
.attr("width", w)
.attr("height", h)
.append("svg:g")
.attr("transform", "translate(" + w / 4 + "," + h / 3 + ")");
vis.append("svg:rect")
.attr("width", w)
.attr("height", h)
.style("stroke", "#000");
d3.json("miserables.json", function(json) {
var link = vis.selectAll("line.link")
.data(json.links);
link.enter().append("svg:line")
.attr("class", "link")
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.source.x; })
.attr("y2", function(d) { return d.source.y; })
.style("stroke-width", function(d) { return (1/(1+d.value))*5 });
var node = vis.selectAll("g.node")
.data(json.nodes);
var nodeEnter = node.enter().append("svg:g")
.attr("class", "node")
.on("mouseover", fade(.1))
.on("mouseout", fade(1))
.call(force.drag);
nodeEnter.append("svg:circle")
.attr("r", r)
.style("fill", function(d) { return z(d.group); })
.style("stroke", function(d) { return
d3.rgb(z(d.group)).darker(); });
nodeEnter.append("svg:text")
.attr("text-anchor", "middle")
.attr("dy", ".35em")
.text(function(d) { return d.name; });
force
.nodes(json.nodes)
.links(json.links)
.on("tick", tick)
.start();
function tick() {
// This works
node.attr("transform", function(d) { return "translate(" + d.x + ","
+ d.y + ")"; });
// This contains the lines within the boundary, but the nodes are
stuck in the top left corner
//node.attr("cx", function(d) { return d.x = Math.max(r, Math.min(w
- r, d.x)); })
// .attr("cy", function(d) { return d.y = Math.max(r, Math.min(h -
r, d.y)); });
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; });
}
var linkedByIndex = {};
json.links.forEach(function(d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1;
});
function isConnected(a, b) {
return linkedByIndex[a.index + "," + b.index] ||
linkedByIndex[b.index + "," + a.index] || a.index == b.index;
}
function fade(opacity) {
return function(d) {
node.style("stroke-opacity", function(o) {
thisOpacity = isConnected(d, o) ? 1 : opacity;
this.setAttribute('fill-opacity', thisOpacity);
return thisOpacity;
});
link.style("stroke-opacity", opacity).style("stroke-opacity",
function(o) {
return o.source === d || o.target === d ? 1 : opacity;
});
};
}
});
3 ответа
В моем выступлении о силовых раскладках есть пример ограничительной рамки. Интеграция положения Verlet позволяет вам определять геометрические ограничения (такие как ограничивающие рамки и обнаружение столкновений) внутри прослушивателя событий "галочка"; просто переместите узлы, чтобы соответствовать ограничению, и симуляция адаптируется соответствующим образом.
Тем не менее, гравитация, безусловно, является более гибким способом решения этой проблемы, поскольку она позволяет пользователям временно перетаскивать график за пределы ограничительной рамки, и затем график восстанавливается. В зависимости от размера графика и размера отображаемой области, вы должны поэкспериментировать с различными значениями относительной силы тяжести и заряда (отталкивания), чтобы привести график в соответствие.
Таможенная сила также является возможным решением. Мне больше нравится этот подход, поскольку не только отображаемые узлы перемещаются, но и вся симуляция работает с ограничивающей силой.
let simulation = d3.forceSimulation(nodes)
...
.force("bounds", boxingForce);
// Custom force to put all nodes in a box
function boxingForce() {
const radius = 500;
for (let node of nodes) {
// Of the positions exceed the box, set them to the boundary position.
// You may want to include your nodes width to not overlap with the box.
node.x = Math.max(-radius, Math.min(radius, node.x));
node.y = Math.max(-radius, Math.min(radius, node.y));
}
}
Прокомментированный код работает на узле, который, по вашему определению, является элементом svg g(rouping) и не управляет атрибутами cx/cy. Выберите элемент круга внутри узла, чтобы эти атрибуты ожили:
node.select("circle") // select the circle element in that node
.attr("cx", function(d) { return d.x = Math.max(r, Math.min(w - r, d.x)); })
.attr("cy", function(d) { return d.y = Math.max(r, Math.min(h - r, d.y)); });