簡體   English   中英

如何將力有向圖重置為其原始 position?

[英]How to reset force directed graph to its original position?

我有一個帶有節點和鏈接的力導向圖,我想在重置后將圖重置為其原始 position。 我設法通過創建另一個圖來實現重置結果,該圖具有力導向圖的坐標: https://jsfiddle.net/Lf0jcnt1/1/

對於重置方法,我使用了這個 function:

  function reset(source) {
    source.selectAll("circle")
      .transition()
      .duration(750)
      .style("fill","red")
      .attr("cx", function(d) {
        console.log("Initial X position from RESET is " + d.c);
        return (d.c)
      })
      .attr("cy", function(d) {
        return (d.z)
      })
  }

像這樣附加數據的地方:

  var circle_data = d3.range(nodes_len).map(function(i) {
    return {
      c: x_nodes[i],
      z:y_nodes[i]
    };
  });

問題是,當單擊重置按鈕時,力有向圖不會將節點 position 重置為原始節點,節點將被平移到與原始位置不同的位置。

下面是強制圖的代碼:

    constructor(nodes: Node[], links: Link[], options: { width: number, height: number }) {
        this.nodes = nodes;
        this.links = links;
        this.options = options;
      
        this.simulation = forceSimulation<Node, Link>()
            .force('links', forceLink(this.links).distance(FORCES.DISTANCE).strength(FORCES.LINKS))
            .force('collide', forceCollide((node: Node) => node.radius * 2 + 30))
            .force('center', forceCenter(this.options.width / 2, this.options.height / 2))
            .force('cluster', forceCluster((node: Node, index: number, data: Node[]) => {
                const numberOfGroups = this.nodes.map(n => n.group).filter((value, i, array) => array.indexOf(value) === i).length;

                for (let i = 0; i < numberOfGroups; i++) {
                    if (node.group === i + 1) {
                        const max = data.filter(n => n.group === i + 1).map(n => n.instancesCount).sort((n1, n2) => n1 - n2).pop();
                        return data.filter(n => n.group === i + 1).filter(n => n.instancesCount === max).pop();
                    }
                }
            }).strength(FORCES.CLUSTER))
            .nodes(this.nodes)
            ;

        this.simulation.on('tick', () => {
            this.ticker.next();
        });

        
        this.simulation.on('end', () => { 
            console.log("end of simulation values);
            this.xNodeValues = this.nodes.map( (node)=> node.x);
            this.yNodeValues = this.nodes.map( (node)=> node.y);
        });

    }

對於力有向圖,我嘗試使用與之前相同的重置方法,但將 c 和 z 替換為 x 和 y,但發生平移效果,而不是重置到原始位置。 關於如何解決這個問題的任何想法?

您可以在初始 position JSON.stringify創建節點的“快照”

this.savedNodes = JSON.stringify(nodes)

單擊重置按鈕后,您可以將其加載回 class 和仿真:

this.nodes = JSON.parse(this.savedNodes)
this.simulation.nodes(this.nodes).restart()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM