如何使用加权邻接矩阵在带有networkx的python中绘制边缘权重?

时间:2019-12-10 22:32:14

标签: python networkx

我有一个问题,我有向图的加权邻接矩阵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)

这会绘制一个图形,并且在顶点上有标签,但是没有边权重-同样,我也无法通过上链接调整技术以使其起作用-那我该怎么办?

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

1 个答案:

答案 0 :(得分:1)

使用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()

结果:

enter image description here