This answer演示如何使用以下代码绘制具有自定义颜色和边缘厚度的图形:
import networkx as nx
G = nx.Graph()
G.add_edge(1,2,color='r',weight=2)
G.add_edge(2,3,color='b',weight=4)
G.add_edge(3,4,color='g',weight=6)
pos = nx.circular_layout(G)
edges = G.edges()
colors = [G[u][v]['color'] for u,v in edges]
weights = [G[u][v]['weight'] for u,v in edges]
nx.draw(G, pos, edges=edges, edge_color=colors, width=weights)
然而,假设我想绘制一个多图,如:
G = nx.MultiGraph()
G.add_edge(1,2,color='r',weight=2)
G.add_edge(1,2,color='b',weight=3)
G.add_edge(2,3,color='r',weight=4)
G.add_edge(2,3,color='b',weight=6)
调用诸如 draw 之类的东西应该总共得到三分。点 1 和点 2 之间应该都有一条红线和蓝线,类似地,点 2 和点 3 之间也应该有一条红线和蓝线。
这不适用于多图,因为多条边需要不同的存储技术。有没有相对简单的方法解决这个问题?
另外,我相信这个question and answer不适用。提问者使用 MultiGraph 对象,但是,实际的图不是多重图。解决方案是选择第一个(并且在他的情况下是唯一的)边缘。然而,在这种情况下,绘图阶段需要两条边。
有没有办法在 networkx 中绘制具有不同颜色和权重的多条边?
请您参考如下方法:
您只需要以不同的方式访问多重图的边缘
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
G = nx.MultiGraph()
G.add_edge(1,2,color='r',weight=8)
G.add_edge(1,2,color='b',weight=3)
G.add_edge(2,3,color='r',weight=4)
G.add_edge(2,3,color='c',weight=6)
pos = nx.circular_layout(G)
edges = G.edges()
colors = []
weight = []
for (u,v,attrib_dict) in list(G.edges.data()):
colors.append(attrib_dict['color'])
weight.append(attrib_dict['weight'])
nx.draw(G, pos, edges=edges, edge_color=colors, width=weight, )
plt.show()
这里是边的另一种组合
G = nx.MultiGraph()
G.add_edge(1,2,color='r',weight=2)
G.add_edge(1,2,color='b',weight=3)
G.add_edge(2,3,color='r',weight=4)
G.add_edge(2,3,color='b',weight=6)
您可以阅读有关访问多图边的更多信息 here .
