绘制宽度与权重成比例的图形

问题描述 投票:-1回答:1

我有一个系统,其中每个节点与所有其他节点都有关系,但是权重不同。例如,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')    
python networkx
1个回答
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 -> BB -> 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.

就表示而言,如果您需要将弧形宽度与其权重进行匹配,则可以使用drawwidth选项。您还需要为图形使用arc表示,以使弧线不会重叠:

pos = nx.spring_layout(G)
edge_widths = [w for (*edge, w) in G.edges.data('weight')]
nx.draw(G, pos, width=edge_widths, connectionstyle='arc3, rad=.15')
© www.soinside.com 2019 - 2024. All rights reserved.