首页 > 解决方案 > 添加边缘权重以从邻接矩阵中绘制 networkx 中的输出

问题描述

我正在生成一个随机图并从邻接矩阵中绘制它。我需要能够添加边缘权重。

我查看了Add edge-weights to plot output in networkx,这似乎工作正常,正是我在显示中寻找的内容,但它仅在单独添加边缘时才有效。

我正在使用:nx.from_numpy_matrix(G, create_using = nx.DiGraph())

并且根据文档,如果非对称邻接矩阵只有整数条目(确实如此),则这些条目将被解释为连接顶点的加权边(不创建平行边)。因此,当查看Add edge-weights to plot output in networkx时,它们会抓取节点属性,抓取标签属性并绘制边缘标签。但是我无法获取属性。有谁知道如何在仍然使用这个邻接矩阵的同时显示这些边缘?

提前致谢!

from random import random
import numpy
import networkx as nx
import matplotlib.pyplot as plt

#here's how I'm generating my random matrix
def CreateRandMatrix( numnodes = int):
    def RandomHelper():
        x = random()
        if x < .70:
            return(0)
        elif .7 <= x and x <.82:
            return(1)
        elif .82 <= x and x <.94:
            return(2)
        else:
            return(3)
    randomatrix = numpy.matrix([[RandomHelper() for x in range(numnodes)] for y in range(numnodes)])
    for i in range(len(randomatrix)):
        randomatrix[i,i]=0
    return randomatrix

#this generate the graph I want to display edge weights on
def Draw(n = int): 
    MatrixtoDraw = CreateRandMatrix(n)
    G = nx.from_numpy_matrix(MatrixtoDraw, create_using = nx.DiGraph())
    nx.draw_spring(G, title="RandMatrix",with_labels=True)
    plt.show()

这是我尝试在 networkx 中添加边权重以绘制输出

def Draw2(n = int):
    MatrixtoDraw = CreateRandMatrix(n)
    G = nx.from_numpy_matrix(MatrixtoDraw, create_using = nx.DiGraph())
    nx.draw_spring(G, title="RandMatrix",with_labels=True)
    pos=nx.get_node_attributes(G,'pos')
    labels = nx.get_edge_attributes(G,'weight')
    nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
    plt.show()

如果我在空闲时单独运行每条线,我会得到

>>> nx.get_node_attributes(G,'pos')
{}
>>> nx.get_node_attributes(G,'weight')
{}

为什么没有从邻接矩阵生成的图信息中抓取它们?

标签: pythonmatplotlibnetworkx

解决方案


推荐阅读