我正在生成一个随机图,并从邻接矩阵中绘制它。我需要能够添加边缘权重。
我看着Add edge-weights to plot output in networkx,它似乎可以正常工作,并且正是我在显示器中寻找的东西,但是它仅在单独添加边缘时才有效。
我正在使用: nx.from_numpy_matrix(G,create_using = nx.DiGraph())
根据the documentation,如果非对称邻接矩阵仅具有整数项(确实如此),则这些项将被解释为连接顶点的加权边(不创建平行边)。因此,在查看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()
这是我追随Add edge-weights to plot output in 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')
{}
为什么不从邻接矩阵生成的图信息中获取它们?