使用 d3 自定义气泡位置



我有一个气泡图,其中包含两种类型的节点,Ip 和 User ,表示为蓝色和粉红色,但这里有数据,我有一个可视化,其中两个节点都混合在一起,如图像 https://i.stack.imgur.com/9IUU6.jpg

但我想用不同的颜色分层它 https://i.stack.imgur.com/5ZrNH.jpg

这是我的工作代码

var nodes = [some dummy data here]
var width = 1000
var height = 600
//Defining colors
var color = d3.scaleOrdinal()
.domain(["user", "IP"])
.range(["#5688F0", "#ff6074"]);
const forceX = d3.forceX(width / 2).strength(0.015)
const forceY = d3.forceY(height / 2).strength(0.015)
var force = d3.forceSimulation()
.velocityDecay(0.2)
.force("x", forceX)
.force("y", forceY)
.force("collide", d3.forceCollide().radius(function (d) {
return (d.edge_count * 0.0055 + 3);
}).iterations(5))
.nodes(nodes).on("tick", ticked);
//Defining the svg
var svg = d3.select(".cichart").append("svg")
.attr("width", width)
.attr("height", height);
//Creating circles
var circles = svg.selectAll("circle")
.data(nodes)
.enter().append("circle")
.attr("r", function (d) { return d.edge_count * 0.0055 })
.style("fill", function (d, i) { return color(i % 3); })
circles.on("mouseover", function (n) {
circles.style("stroke", function (d) {
if (d.id == n.id)
return "black";
else
return "white";
})
circles.style("stroke-width", function (d) {
if (d.id == n.id)
return 2;
else
return 0;
})
labelbox(n)
})
function labelbox(d) {
var view = d3.select('#abc')
view.html(`<div>Label :${d.node_label}</div> <div>Number of connections :${d.edge_count}</div>  `)
}
function ticked(e) {
svg.selectAll("circle")
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; });
};

您可以在 forceX 和 forceY 中指定一个"位置",因此执行以下操作:

const forceX = d3.forceX(function(d) {
const position = d.group === "user" ? -100 : 100;
return position;
}).strength(0.15)

将根据组设置节点位置。

另一方面,您没有根据组设置节点颜色(也许我错过了一些东西(,但我会这样做:

.style("fill", function (d, i) {
return color(d.group);
});

下面是一个带有工作代码的可观察笔记本:

链接

最新更新