使用 networkx 有多种方法可以做到这一点 - 这是一个适合您要求的解决方案:
代码:
# Set up weighted adjacency matrix
A = np.array([[0, 0, 0],
[2, 0, 3],
[5, 0, 0]])
# Create DiGraph from A
G = nx.from_numpy_matrix(A, create_using=nx.DiGraph)
# Use spring_layout to handle positioning of graph
layout = nx.spring_layout(G)
# Use a list for node_sizes
sizes = [1000,400,200]
# Use a list for node colours
color_map = ['g', 'b', 'r']
# Draw the graph using the layout - with_labels=True if you want node labels.
nx.draw(G, layout, with_labels=True, node_size=sizes, node_color=color_map)
# Get weights of each edge and assign to labels
labels = nx.get_edge_attributes(G, "weight")
# Draw edge labels using layout and list of labels
nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=labels)
# Show plot
plt.show()
结果:
