NetworkX中的网络图未在视觉上进行优化

时间:2016-10-17 17:33:12

标签: python graph visualization networkx

我刚接触NetworkX,所以我可能做错了。我正在尝试使用从wikipedia.org抓取的数据创建简单的图表。下面是我使用spring_layout选项构建的简单图的示例。这是预期的那种输出吗?我在想它会重新安排点以避免交叉线,以使它看起来更简单。它似乎根本没有试图避免过境。

另外,我想要更多的流程图从左到右,如this(每个点都有年份值)(或垂直),但是doesn't seem to be possible in NetworkX。任何人都可以确认吗?在我看来,线性流程图是一种常见的需求。

enter image description here

此示例中的数据:

selected_nodes = [96, 64, 163, 132, 166, 138, 108, 141, 238, 50, 58, 60, 61, 223]

selected_edges = [
    (50, 58),
    (61, 64),
    (60, 64),
    (58, 96),
    (108, 132),
    (96, 141),
    (138, 163),
    (141, 163),
    (64, 166),
    (163, 223),
    (132, 238),
    (96, 238),
    (166, 238),
    (223, 238)
]

text_labels = {
    50: u'ALGOL 58 (IAL)',
    58: u'ALGOL 60',
    60: u'COMIT (implementation)',
    61: u'FORTRAN IV',
    64: u'SNOBOL',
    96: u'ALGOL 68 (UNESCO/IFIP standard)',
    108: u'SETL',
    132: u'ABC',
    138: u'Modula',
    141: u'Mesa',
    163: u'Modula-2',
    166: u'Icon (implementation)',
    223: u'Modula-3',
    238: u'Python'
}

脚本代码

# This visualisation creates a network graph 
# with the spring layout

import networkx as nx
import matplotlib.pyplot as plt  

G = nx.DiGraph() # Create an empty Graph

G.add_nodes_from(selected_nodes)
G.add_edges_from(selected_edges)

plt.figure(1,figsize=(15,15))
#nx.draw(G, node_color='c', edge_color='k', with_labels=True)

pos = nx.spring_layout(G)

plt.figure(1,figsize=(15,15))

nx.draw_networkx_nodes(G, pos, labels=True)
nx.draw_networkx_edges(G, pos, arrows=True)
#nx.draw_networkx_labels(G, pos, labels)

for p, values in pos.iteritems():
    x, y = values
    plt.text(x+0.04, y+0.02, s=text_labels[p], horizontalalignment='center')

plt.savefig('lang_predecessors.pdf')
plt.show()

1 个答案:

答案 0 :(得分:3)

The graphviz dot layout has a hierarchical layout.  If you install pygraphviz you can use it like this

import networkx as nx
import matplotlib.pyplot as plt
from networkx.drawing.nx_agraph import to_agraph

selected_nodes = [96, 64, 163, 132, 166, 138, 108, 141, 238, 50, 58, 60, 61, 223]

selected_edges = [
    (50, 58),
    (61, 64),
    (60, 64),
    (58, 96),
    (108, 132),
    (96, 141),
    (138, 163),
    (141, 163),
    (64, 166),
    (163, 223),
    (132, 238),
    (96, 238),
    (166, 238),
    (223, 238)
]

text_labels = {
    50: u'ALGOL 58 (IAL)',
    58: u'ALGOL 60',
    60: u'COMIT (implementation)',
    61: u'FORTRAN IV',
    64: u'SNOBOL',
    96: u'ALGOL 68 (UNESCO/IFIP standard)',
    108: u'SETL',
    132: u'ABC',
    138: u'Modula',
    141: u'Mesa',
    163: u'Modula-2',
    166: u'Icon (implementation)',
    223: u'Modula-3',
    238: u'Python'
}
G = nx.DiGraph() # Create an empty Graph

for k,v in text_labels.items():
    G.add_node(k,label=v)
G.add_edges_from(selected_edges)

A = to_agraph(G)

A.draw('lang_predecessors.png', prog='dot')

enter image description here