Python笔记——nextworkx有向图

环境:ubuntu16.04,python2.7.12

版本:networkx==2.2, matplotlib==1.5.1, numpy==1.11.0

官方文档:https://networkx.github.io/documentation/networkx-2.2/

参考:https://www.cnblogs.com/minglex/p/9205160.html

创建图

import networkx as nx
graph = nx.DiGraph()

节点

添加节点:

graph.add_node(1)
graph.add_node(2, value=float('inf'))

查看节点属性:

graph.node[2]

返回{'value': inf},为dict类型。

修改/添加节点属性:

graph.node[2]['value'] = 7

遍历节点: 

graph.node(data=True)
graph.nodes(data=True)

结果均为:

[(1, {}), (2, {'value': 7})]


添加边:

graph.add_edge(1, 2, weight=9.0)

查看边属性:

graph[1][2]['weight']

修改/添加节点属性:

graph[1][2]['length'] = 10

遍历边:

graph.edges(data=True)

结果为

[(1, 2, {'length': 10, 'weight': 9.0})]


可视化

若指定节点位置,需首先给出位置dict:

keys = [node for index, node in enumerate(graph.nodes)]
positions = np.array([(1,1), (2,2)])
pos = dict(zip(keys, positions))

其次:

edge_width = 1.0

nx.draw_networkx_nodes(graph, pos)
nx.draw_networkx_labels(graph, pos)
nx.draw_networkx_edges(graph, pos, width=edge_width, arrowstyle='->')

plt.show()

效果:

  • 不指定节点位置:
pos = nx.spring_layout(graph)

其中,spring_layout可替换。

  • 根据边权重改变边的粗细:
edge_width = [float(d['weight']*1.0) for (u,v,d) in graph.edges(data=True)]
  • 显示边的属性:
edge_labels = dict([((u,v,),d['weight']) for u,v,d in graph.edges(data=True)])
nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels)

效果:


附(源码)

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np


graph = nx.DiGraph()

graph.add_node(1)
graph.add_node(2, value=float('inf'))
graph.node[2]['value'] = 7

graph.add_edge(1, 2, weight=9.0)
graph[1][2]['length'] = 10


keys = [node for index, node in enumerate(graph.nodes)]
positions = np.array([(1,1), (2,2)])
pos = dict(zip(keys, positions))

edge_width = 1.0

nx.draw_networkx_nodes(graph, pos)
nx.draw_networkx_labels(graph, pos)
nx.draw_networkx_edges(graph, pos, width=edge_width, arrowstyle='->')

edge_labels = dict([((u,v,),d['weight']) for u,v,d in graph.edges(data=True)])
nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels)

plt.show()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值