Drawing nested network diagrams
I would like to know if there is a way to draw nested networkx plots in python.
I can successfully execute these plots by calling the nx.draw _ (...) method as described in the networkx files, but in the case where I use it, it requires one of the nodes to be a plot by itself (imagine a network of rooms , on the upper level with the zone / zone network in these rooms on the next level down). I would like to show this using matplotlib or similar.
Any ideas would be appreciated.
source to share
Edit You can probably do better than my original answer by defining a recursive function. Here's an example of what a recursive function would look like. My answer below gives a less elegant approach that can be easily customized for a specific case, but if you ever do this often, you will probably need 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 a recursive function please add it as a separate answer and give me a comment. I'll point it out from this answer.
Original answer Here's the first pass (I hope by editing the full answer before the end of the day, but I think this will give you most of the way):
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 center each subzone. This will require defining xmin, xmax, ymin and ymax for each subheading and adjustment. You can play with the scalefactor as well.
source to share