I'm generating a random graph and drawing it from the adjacency matrix. I need to be able to add the edge weights.
I looked at Add edge-weights to plot output in networkx and that seems to work fine and is exactly what I'm looking for in the display, but it only works when adding edges individually.
I'm using: nx.from_numpy_matrix(G, create_using = nx.DiGraph())
And according to the documentation, if the nonsymmetric adjacency matrix has only integer entries (which it does), the entries will be interpreted as weighted edges joining the vertices (without creating parallel edges). So when looking at Add edge-weights to plot output in networkx, they grab the node attributes, grab the label attributes, and draw the edge labels. But I'm unable to grab the attributes. Does anyone know how to display these edges while still using this adjacency matrix?
Thanks in advance!
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()
This my attempt at following 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()
If I run each line individually on idle I get
>>> nx.get_node_attributes(G,'pos')
{}
>>> nx.get_node_attributes(G,'weight')
{}
Why are they not being grabbed from the graph information generated by the adjacency matrix?