javascript - 力模拟和组网络图
问题描述
我有一个以下 json
{
"nodes": [
{
"type_a": 1,
"type_b": "A",
"type_c": "1234",
},
{
"type_a": 2,
"type_b": "B",
"type_c": "1234",
},
{
"type_a": 3,
"type_b": "B",
"type_c": "1111",
},
{
"type_a": 1,
"type_b": "B",
"type_c": "1222",
}
],
"links": [
{
}
]
}
我想在用户单击按钮时根据类型对节点进行分组。所以,我为每种类型设置了三个按钮
这是代码:
var buttons = d3.select("#option").selectAll("button")
.data(["type_a","type_b","type_c"])
.enter()
.append("button")
.text(function(d) { return d; })
d3.json("data.json", function(error, graph) {
if (error) throw error;
const svg = d3.select('#chart3'),
width = +svg.attr('width'),
height = +svg.attr('height');
let simulation = d3.forceSimulation()
.nodes(graph.nodes)
.force('collision', d3.forceCollide().radius(15))
.force('center', d3.forceCenter(width / 2, height / 2))
.on('tick', ticked);
buttons.on("click", function() {
var x = d3.scaleOrdinal()
.domain([1,20])
.range([50, 100,200,300,400,500,600,700, 800, 900,1000, 1100,1200])
if (a=='type_a'){
simulation.force("x", d3.forceX().strength(0.5).x( function(d){ return x(d.type_a)} ))
simulation.force("forceY", d3.forceY().strength(.1).y(height * .5))
simulation.force('collision', d3.forceCollide().radius(15))
}
else if (a=='type_b') {
simulation.force("x", d3.forceX().strength(0.5).x( function(d){ return x(d.type_b)} ))
simulation.force("forceY", d3.forceY().strength(.1).y(height * .5))
simulation.force('collision', d3.forceCollide().radius(15))
}
else if (a=='type_c') {
simulation.force("x", d3.forceX().strength(0.5).x( function(d){ return x(d.type_c)} ))
simulation.force("forceY", d3.forceY().strength(.1).y(height * .5))
simulation.force('collision', d3.forceCollide().radius(15))
}
simulation
.alpha(0.5)
.alphaTarget(0.3)
.restart();
})
我不知道如何对它进行分组,所以我使用了 d3.forceX()。当我单击该按钮时,它实际上对节点进行了分组,但将它们水平放置并且仅包含 10 个组。
我想让它们在整个地方随机分组,而不仅仅是水平。
另外,我不知道每种类型会有多少个值,因此会有多少组,所以我不确定如何处理 ScaleOrdinal 值。
解决方案
推荐阅读
- c++ - 接受矩阵 col 和向量的特征模板函数
- javascript - 尽管控制台没有显示错误,但反应功能组件没有呈现
- python - 使用 Python 查找均值、众数和中位数
- javascript - 我的 handler.js 文件中未定义 Express 服务器处理程序“app”
- html - 当我尝试添加行高时;?px; 它弄乱了页面
- javascript - jQuery:如何使 jQuery 代码在新构建的 Modal 中运行
- angular - EsriLoader 和 Angular:没有边界和街道的底图
- python - 如何导入顶级文件夹中的文件?
- fingerprint - 如何让 fprint 为 su 工作,它为 sudo 工作
- php - 在 PDO 中动态 WHERE 子句查询后计算特定行数