我有一个问题,我有一个有向图的加权邻接矩阵 C,因此 C(j,i)=0,只要从 j 到 i 没有边并且 C(j,i)>0,则C(j,i)为边的权重;
现在我想绘制有向图。手动添加边缘时有很多解决方案,请参见例如这里:
Add edge-weights to plot output in networkx
但我想根据我的矩阵 C 绘制边和边权重;我开始采用以下方式:
def DrawGraph(C):
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph(C)
plt.figure(figsize=(8,8))
nx.draw(G, with_labels=True)
这绘制了一个图表,顶点上有标签,但没有边权重 - 而且我无法调整上部链接的技术以使其工作 - 那么我能做什么?
如何更改节点大小和颜色?
最佳答案
使用 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()
结果:
关于python - 如何使用加权邻接矩阵绘制边权重?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59276335/