Saurabh Pandey
Saurabh Pandey

Reputation: 21

How to keep nodes fixed while adding nodes at other locations in a tree structure?

I am making a kind of program in which nodes are added dynamically in a tree structure using Animation in Networkx Python. The code is working fine without any error, but every time a new node is added the layout or design of the graph changes, I want to make it static.

Can I do it with graphviz layout having the initial position of previous nodes as fixed?

import os, sys
import networkx
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import random

def draw():
    mote_color = []
    mote_list = []
    G = networkx.Graph()
    nodes_list = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
    node = random.choice(nodes_list)


    def animate(self):
        plt.clf()
        node = random.choice(nodes_list)
        mote_list.append(node)
        G.add_node("BR")
        for node in mote_list:
            G.add_node(node)
            G.add_edge("BR",node)
        print(mote_list)
        pos = networkx.graphviz_layout(G)
        networkx.draw(G,pos,nodelist=["BR"],node_shape="p",node_size=2000)
        networkx.draw(G,pos,nodelist=mote_list,node_shape="s",node_size=500)


    fig = plt.figure(figsize=(16,12))
    plt.clf()
    anim = animation.FuncAnimation(fig, animate, frames=20, interval=2000, blit=False)
    plt.show()


draw()

Upvotes: 0

Views: 516

Answers (1)

Joel
Joel

Reputation: 23907

This command: pos = networkx.graphviz_layout(G) recalculates the positions for all the nodes. So each time you call it in your loop, all the nodes get new positions.

If possible, the best option would be to create the entire graph and calculate pos. Then plot them adding one node at a time.

But if you don't know what the graph looks like in advance, you can't do this. In this case what you'll want to do is come up with your own way to define the dict pos. So when you add a new node v, you'll have to define pos[v]. An obvious problem with this is that at the end, the network may look quite messy because you don't know what the best layout will look like at the end.

More details specifically to graphviz are at this question. It is possible to use spring_layout and specify that the existing nodes remain fixed by pos = nx.spring_layout(G, fixed=list_of_fixed_nodes)

Upvotes: 1

Related Questions