首页 > 解决方案 > 力模拟和组网络图

问题描述

我有一个以下 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 值。

标签: javascriptjqueryd3.js

解决方案


推荐阅读