使用d3自定义气泡位置

时间:2019-09-05 07:40:05

标签: javascript html css d3.js

我有一个气泡图,其中有两个类型的节点Ip和User,分别表示为蓝色和粉红色,但是在这里,我有一个可视化的数据,其中两个节点都混合在一起,如图像https://imgur.com/a/3Xx9KE3

但是我想用不同的颜色https://imgur.com/a/BRAxlUj

这是我的工作代码

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; });
};

1 个答案:

答案 0 :(得分:1)

您可以在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);
});

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

Link