如何在python中使用networkx绘制有向图?

时间:2023-02-01 23:57:34

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). This is basically, like a path from A to D when all other nodes are present. you can imagine each nodes as cities and travelling from A to D requires directions (with arrow heads). This code below builds the graph

我有一些节点来自我想要映射到图表的脚本。在下面,我想使用箭头从A到D,并且边缘也可能是彩色的(红色或其他东西)。这基本上就像当存在所有其他节点时从A到D的路径。您可以将每个节点想象成城市,从A到D行进需要方向(带箭头)。下面的代码构建了图表

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.如何在python中使用networkx绘制有向图?如何在python中使用networkx绘制有向图?

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

Arrow heads of the first image and the edges in red color onto the second image..Thanks

第一张图像的箭头和第二张图像的红色边缘。谢谢

5 个解决方案

#1


54  

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()

如何在python中使用networkx绘制有向图?

#2


37  

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笔记本渲染这个我不得不直接从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()

如何在python中使用networkx绘制有向图?

#3


17  

You need to use a directed graph instead 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。

如何在python中使用networkx绘制有向图?

#4


6  

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 parameter In this case this state is the default one:

还有一些函数支持directed = True参数。在这种情况下,这个状态是默认状态:

G = nx.DiGraph(directed=True)

The networkx reference is found here.

可以在此处找到networkx参考。

如何在python中使用networkx绘制有向图?

#5


5  

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.

因此再次绘制。

#1


54  

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()

如何在python中使用networkx绘制有向图?

#2


37  

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笔记本渲染这个我不得不直接从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()

如何在python中使用networkx绘制有向图?

#3


17  

You need to use a directed graph instead 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。

如何在python中使用networkx绘制有向图?

#4


6  

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 parameter In this case this state is the default one:

还有一些函数支持directed = True参数。在这种情况下,这个状态是默认状态:

G = nx.DiGraph(directed=True)

The networkx reference is found here.

可以在此处找到networkx参考。

如何在python中使用networkx绘制有向图?

#5


5  

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.

因此再次绘制。