xyz*_*zen 3 python tree graph matplotlib networkx
我想知道是否有办法在python中绘制嵌套的networkx图.
我可以使用 networkx文档中描述的nx.draw _(...)方法调用成功绘制这些图形 ,但是我使用它的情况要求其中一个节点本身就是一个图形(想象一下房间网络) ,在顶层,在下一层的房间内有一个区域/区域网络).我想用matplotlib或类似的方式来展示这个.
任何想法,将不胜感激.
编辑 通过定义递归函数,您可能比我原来的答案做得更好.这是递归函数看起来如何的大致轮廓.我在下面的回答给出了一个不太优雅的方法,可以轻松调整特定情况,但如果你经常这样做,你可能会想要这个递归版本.
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)
Run Code Online (Sandbox Code Playgroud)
如果有人创建了递归函数,请将其作为单独的答案添加,并给我一个评论.我会从这个答案中指出它.
原始答案 这是第一遍(我希望在一天结束时编辑完整的答案,但我认为这会让你大部分时间都在那里):
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')
Run Code Online (Sandbox Code Playgroud)

我认为你应该做的另一件事是将每个子节点集中在一起.这将需要识别每个子图的xmin,xmax,ymin和ymax并进行调整.您可能还想使用scalefactor.
| 归档时间: |
|
| 查看次数: |
991 次 |
| 最近记录: |