【问题标题】:How to draw edge weights using a weighted adjacency matrix?如何使用加权邻接矩阵绘制边缘权重?
【发布时间】:2020-04-04 04:15:16
【问题描述】:

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

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

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

【问题讨论】:

    标签: python matplotlib networkx graph-theory adjacency-matrix


    【解决方案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()
    

    结果:

    【讨论】:

    • 使用完全相同的 A,当我使用命令“G = nx.from_numpy_matrix(A, create_using=nx.DiGraph)”时出现错误:“输入图不是 networkx 图类型” - 是否可能缺少某种包裹?
    • @Ivan 如果将括号添加到nx.DiGraph,您会得到同样的错误吗?如下:G = nx.from_numpy_matrix(A, create_using=nx.DiGraph())
    猜你喜欢
    • 1970-01-01
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多