如何使用加权邻接矩阵绘制边权重?

How to draw edge weights using a weighted adjacency matrix?

我有一个有向图的加权邻接矩阵 C 的问题,所以 C(j,i)=0,只要没有从 j 到 i 的边并且如果 C(j,i)> 0,则C(j,i)为边的权重;

现在我想绘制有向图。手动添加边时有很多解决方案,请参见例如这里:

但我想根据我的矩阵 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)

这绘制了一个图,顶点上有标签,但没有边权重 - 我也无法调整上层 link 的技术来使其工作 - 那我该怎么办?

我该如何更改节点大小和颜色?

有多种方法可以使用 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()

结果: