使用 networkx + graphviz 定位/显示标签 [英] Position/showing of labels with networkx + graphviz

查看:49
本文介绍了使用 networkx + graphviz 定位/显示标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I've achieved the following plot with a combination networkx and graphviz:

I'm very happy with the result. In the plot you can identify what I call aggregation nodes: those are the latest green ones (where all the green nodes converge) one hop before the orange ones.

What I'd like to achieve is the following:

1) Put labels on the sides of the nodes. As you can see, the labels are over them and it's difficult to read;

2) Only show labels on the aggregation nodes and the orange ones.

This is how I get to plot the diagram.

# We create the graph
G = nx.DiGraph()

# We add nodes and edges
G.add_nodes_from(nodes)
G.add_edges_from(edges)

# We establish attributes to nodes
nx.set_node_attributes(G,nodesAttrDic)

# Tune plot
nodeFontSize    = 10
nodeSize        = 20
nodeColorList   = list(getNodeColor(nodesAttrDic,G.nodes()))
edgeColorList   = getEdgeColor(G.edges())

# Graphiz tunning
prog = 'dot'
args = '-Gnodesep=1 -Granksep=2 -Gpad=0.5 -Grankdir=TD'
root = None
pos  = graphviz_layout(G, prog = prog, root = root, args = args)

nx.draw(G,
    pos         = pos,
    with_labels = True, 
    node_color  = nodeColorList, 
    edge_color  = edgeColorList, 
    font_size   = nodeFontSize,
    node_size   = nodeSize,)

plt.show()

Any ideas on how to do this?

Thanks!

Lucas

解决方案

Ok, so I've partially solved the second question: how to plot from the aggregation nodes onwards. To do so I estimate the number of hops towards the latest one. After that I decide to label the nodes below the threshold.

def getHopToNH(nodes):
    path        = []
    labelList   = {}

    for startNode in G.nodes():
        endNode = 'myLabel'
        try:
            p = len(nx.shortest_path(G,source=startNode,target=endNode))
        except:
            p = -1
        path.append((startNode,p))

        if p < 8:
            labelList = {**labelList,**{str(startNode):str(startNode)}}
        else:
            labelList = {**labelList,**{str(startNode):''}}

    return labelList

UPDATE:

Now, in order to re-position the labels, I had to modify the position myself.

for p in pos:

    yOffSet = -300
    xOffSet = -400

    pos[p] = (pos[p][0]+xOffSet,pos[p][1]+yOffSet)

labelDescr = nx.draw_networkx_labels(G,
    pos         = pos,
    labels      = nodeLabelDict,
    font_size   = nodeFontSize,)

for n,t in labelDescr.items():
    finDegree = 70
    t.set_rotation(finDegree)

After this, I get to plot the following:

And I really like this output now ... :-)

这篇关于使用 networkx + graphviz 定位/显示标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆