简体   繁体   中英

Drawing nested networkx graphs

I would like to know if there is a way to draw nested networkx graphs in python.

I can successfully draw these graphs using the nx.draw_(...) method call as described in the networkx docs, but the case I'm using it for requires that one of the nodes itself is a graph (Imagine a network of rooms, at the top level with a network of areas/zones within those rooms at the next level down). I would like to show this using matplotlib or similar.

Any ideas would be appreciated.

Edit You can probably do better than my original answer by defining a recursive function. Here is a rough outline of how that recursive function would look. My answer below gives a less elegant approach that can be easily tuned for a specific case, but if you're ever doing this frequently, you'll probably want this recursive version.

def recursive_draw(G,currentscalefactor=0.1,center_loc=(0,0),nodesize=300, shrink=0.1):
    pos = nx.spring_layout(G)
    scale(pos,currentscalefactor) #rescale distances to be smaller
    shift(pos,center_loc) #you'll have to write your own code to shift all positions to be centered at center_loc
    nx.draw(G,pos=pos, nodesize=nodesize)
    for node in G.nodes_iter():
        if type(node)==Graph: # or diGraph etc...
            recursive_draw(node,currentscalefactor=shrink*currentscalefactor,center_loc=pos[node], nodesize = nodesize*shrink, shrink=shrink)

If anyone creates the recursive function, please add it as a separate answer, and give me a comment. I'll point to it from this answer.


Original answer Here's a first pass (I'll hopefully edit to a complete answer by end of day, but I think this will get you most of the way there):

import networkx as nx
import pylab as py

G = nx.Graph()

H = nx.Graph()
H.add_edges_from([(1,2), (2,3), (1,3)])

I = nx.Graph()
I.add_edges_from([(1,3), (3,2)])


G.add_edge(H,I)

Gpos = nx.spring_layout(G)
Hpos = nx.spring_layout(H)
Ipos = nx.spring_layout(I)

scalefactor = 0.1
for node in H.nodes():
    Hpos[node] = Hpos[node]*scalefactor + Gpos[H]

for node in I.nodes():
    Ipos[node] = Ipos[node]*scalefactor + Gpos[I]


nx.draw_networkx_edges(G, pos = Gpos)
nx.draw_networkx_nodes(G, pos = Gpos, node_color = 'b', node_size = 15000, alpha = 0.5)
nx.draw(H, pos = Hpos, with_labels = True)
nx.draw(I, pos = Ipos, with_labels = True)
py.savefig('tmp.png')

在此输入图像描述

The main additional thing I think you should do is to center each subnode. This would require identifying xmin, xmax, ymin, and ymax for each subplot and adjusting. You may also want to play with the scalefactor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM