我尝试使用networkX绘制一个“网络图”,但是told,这个库并不是出于我想要用它的目的。
总结上面提到的失败问题,我从我想要绘制的数据开始,然后继续讨论实际问题:
graph = {
'1': ['2', '3', '4'],
'2': ['5','11','12','13','14','15'],
'3' : ['6','7','66','77'],
'5': ['6', '8','66','77'],
'4': ['7','66','77'],
'7': ['9', '10']
}
将此数据视为defaultdict(列表),最左边的部分是键,右侧的列表是该键的值列表。我想要实现的是绘制图形,类似于网络图here:边缘越多,节点越大,标记节点等。
然而,不同之处在于我想要连接键,具有相应的值(1表示2,1表示3,1表示4),但不键彼此(不 1与2与3与5与4与7)。
将数据映像为服务器和客户端。密钥是服务器,值是客户端。服务器(密钥)不直接相互连接,它们只共享(有时)相同的客户端。在上面的示例中,服务器3和服务器5都连接到客户端6,66和77.这也是为什么客户端(值)不应该彼此连接的原因。
我希望能够清楚地表达我的问题^^
谢谢!
答案 0 :(得分:2)
The problem is you're trying to use the same IDs for your servers and clients. NetworkX has no way to know if 2
refers to a client (that should be connected) or a server (that should not). To do what you're describing here, you just need to create a unique id for the servers. For example:
import networkx
graph = {
'1': ['2', '3', '4'],
'2': ['5','11','12','13','14','15'],
'3': ['6','7','66','77'],
'5': ['6', '8','66','77'],
'4': ['7','66','77'],
'7': ['9', '10']
}
g = networkx.Graph()
for k, vs in graph.items():
server_id = 'server_%s' % k
for v in vs:
g.add_edge(server_id,v)
networkx.draw_spring(g)
This produces the following output:
To change the size of node by the number of edges, you need to calculate the size and pass it to draw_spring
. To get the number of edges for a particular node you can call g.edges(node)
e.g.
node_sizes = [150*len(g.edges(n)) for n in g.nodes()]
networkx.draw_spring(g, node_size=node_sizes)
Which should give you the following: