如何在python中使用networkx绘制有向图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20133479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to draw directed graphs using networkx in python?
提问by brain storm
I have some nodes coming from a script that I want to map on to a graph. In the below, I want to use Arrow to go from A to D and probably have the edge colored too in (red or something).
我有一些节点来自我想映射到图形的脚本。在下面,我想使用箭头从 A 转到 D,并且可能将边缘着色为(红色或其他颜色)。
This is basically, like a path from A to D when all other nodes are present. you can imagine each nodes as cities and traveling from A to D requires directions (with arrow heads).
这基本上就像当所有其他节点都存在时从 A 到 D 的路径。你可以把每个节点想象成城市,从 A 到 D 旅行需要方向(带箭头)。
This code below builds the graph
下面的代码构建了图形
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edges_from(
[('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])
val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}
values = [val_map.get(node, 0.25) for node in G.nodes()]
nx.draw(G, cmap = plt.get_cmap('jet'), node_color = values)
plt.show()
but I want something like shown in the image.

但我想要像图中所示的东西。

Arrow heads of the first image and the edges in red color onto the second image.
第一个图像的箭头和红色的边缘到第二个图像上。
采纳答案by Marius
Fully fleshed out example with arrows for only the red edges:
完全充实的示例,仅红色边缘带有箭头:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_edges_from(
[('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])
val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}
values = [val_map.get(node, 0.25) for node in G.nodes()]
# Specify the edges you want here
red_edges = [('A', 'C'), ('E', 'C')]
edge_colours = ['black' if not edge in red_edges else 'red'
for edge in G.edges()]
black_edges = [edge for edge in G.edges() if edge not in red_edges]
# Need to create a layout when doing
# separate calls to draw nodes and edges
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'),
node_color = values, node_size = 500)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
plt.show()
回答by mdml
You need to use a directed graphinstead of a graph, i.e.
您需要使用有向图而不是图,即
G = nx.DiGraph()
Then, create a list of the edge colors you want to use and pass those to nx.draw(as shown by @Marius).
然后,创建要使用的边缘颜色列表并将它们传递给nx.draw(如@Marius 所示)。
Putting this all together, I get the image below. Still not quite the other picture you show (I don't know where your edge weights are coming from), but much closer! If you want more control of how your output graph looks (e.g. get arrowheads that look like arrows), I'd check out NetworkX with Graphviz.
把这一切放在一起,我得到了下面的图片。仍然不是你展示的另一张照片(我不知道你的边缘权重来自哪里),但更接近!如果您想更多地控制输出图的外观(例如获得看起来像箭头的箭头),我会使用 Graphviz 来查看NetworkX。


回答by Back2Basics
I only put this in for completeness. I've learned plenty from marius and mdml. Here are the edge weights. Sorry about the arrows. Looks like I'm not the only one saying it can't be helped. I couldn't render this with ipython notebook I had to go straight from python which was the problem with getting my edge weights in sooner.
我只是为了完整起见。我从 marius 和 mdml 学到了很多东西。这是边缘权重。对不起箭头。看来我不是唯一一个说它无能为力的人。我无法用 ipython notebook 渲染它,我不得不直接从 python 开始,这是更快地获得边缘权重的问题。
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pylab
G = nx.DiGraph()
G.add_edges_from([('A', 'B'),('C','D'),('G','D')], weight=1)
G.add_edges_from([('D','A'),('D','E'),('B','D'),('D','E')], weight=2)
G.add_edges_from([('B','C'),('E','F')], weight=3)
G.add_edges_from([('C','F')], weight=4)
val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}
values = [val_map.get(node, 0.45) for node in G.nodes()]
edge_labels=dict([((u,v,),d['weight'])
for u,v,d in G.edges(data=True)])
red_edges = [('C','D'),('D','A')]
edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]
pos=nx.spring_layout(G)
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw(G,pos, node_color = values, node_size=1500,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
pylab.show()


回答by Padmalochan Panda
import networkx as nx
import matplotlib.pyplot as plt
g = nx.DiGraph()
g.add_nodes_from([1,2,3,4,5])
g.add_edge(1,2)
g.add_edge(4,2)
g.add_edge(3,5)
g.add_edge(2,3)
g.add_edge(5,4)
nx.draw(g,with_labels=True)
plt.draw()
plt.show()
This is just simple how to draw directed graph using python 3.x using networkx. just simple representation and can be modified and colored etc. See the generated graph here.
这只是如何使用 networkx 使用 python 3.x 绘制有向图的简单方法。只是简单的表示,可以修改和着色等。请参阅此处生成的图表。
Note: It's just a simple representation. Weighted Edges could be added like
注意:这只是一个简单的表示。可以添加加权边,例如
g.add_edges_from([(1,2),(2,5)], weight=2)
and hence plotted again.
因此再次绘制。
回答by Raz
Instead of regular nx.draw you may want to use:
您可能想要使用代替常规的 nx.draw:
nx.draw_networkx(G[, pos, arrows, with_labels])
For example:
例如:
nx.draw_networkx(G, arrows=True, **options)
You can add options by initialising that ** variable like this:
您可以通过初始化该 ** 变量来添加选项,如下所示:
options = {
'node_color': 'blue',
'node_size': 100,
'width': 3,
'arrowstyle': '-|>',
'arrowsize': 12,
}
Also some functions support the directed=True parameterIn this case this state is the default one:
还有一些函数支持directed=True parameter在这种情况下这种状态是默认的:
G = nx.DiGraph(directed=True)
The networkx reference is found here.
可在此处找到 networkx 参考。


回答by Sachin Rawat
import networkx as nx
G = nx.DiGraph()
G.add_node("A")
G.add_node("B")
G.add_node("C")
G.add_node("D")
G.add_node("E")
G.add_node("F")
G.add_node("G")
G.add_edge("A","B")
G.add_edge("B","C")
G.add_edge("C","E")
G.add_edge("C","F")
G.add_edge("D","E")
G.add_edge("F","G")
print(G.nodes())
print(G.edges())
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edge_color='r', arrows = True)
plt.show()

