我有一个系统,其中每个节点与所有其他节点都有关系,但是权重不同。 例如,A-> B的权重为0.5,B-> A的权重为2。 下面的示例绘制一个有向图,但是边缘之间没有视觉区别。
我希望线的宽度取决于相应的边缘权重。
from itertools import combinations
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
fig2 = plt.figure(figsize=(15.0, 10.0))
node_names = ['A', 'B', 'C', 'D'] # Get a list of only the node names
G = nx.DiGraph()
G.add_nodes_from(node_names)
for var in combinations(node_names,2):
G.add_edge(var[0], var[1], weight = np.random.uniform(0, 4))
G.add_edge(var[1], var[0], weight = np.random.uniform(0, 4))
e = [(u, v) for (u, v, d) in G.edges(data=True)]
pos = nx.spring_layout(G) # positions for all nodes
# nodes
nx.draw_networkx_nodes(G, pos, node_size=200)
# edges
nx.draw_networkx_edges(G, pos, edgelist=e,width=2)
# labels
nx.draw_networkx_labels(G, pos, font_size=20, font_family='sans-serif')
答案 0 :(得分:0)
它对我有用,请尝试以下操作以确保您遇到问题:
from itertools import combinations
import random
import networkx as nx
random.seed(0)
node_names = ['A', 'B', 'C', 'D']
G = nx.DiGraph()
G.add_nodes_from(node_names)
for (u, v) in combinations(node_names, 2):
G.add_edge(u, v, weight = random.uniform(0, 4))
G.add_edge(v, u, weight = random.uniform(0, 4))
for (u, v, weight) in G.edges.data('weight'):
print(f"Edge {u} -> {v} weights {weight}.")
例如,您应该在其中看到A -> B
与B -> A
不同:
Edge A -> B weights 3.3776874061001925.
Edge A -> C weights 1.68228632332338.
Edge A -> D weights 2.045098885474434.
Edge B -> A weights 3.03181761176121.
就表示形式而言,如果需要将弧形宽度与其权重进行匹配,则可以使用draw
的{{1}}选项。您还需要为图形使用width
表示法,以使弧线不会重叠:
arc