Search code examples
pythonmatplotlibnetworkxgraph-theoryadjacency-matrix

How to draw edge weights using a weighted adjacency matrix?


I have the problem that I have a weighted adjacency matrix C of a directed graph, so C(j,i)=0, whenever there is no edge from j to i and if C(j,i)>0, then C(j,i) is the weight of the edge;

Now I want to plot the Directed Graph. There are many solutions when you manually add edges, see e.g. here:

Add edge-weights to plot output in networkx

But I want to plot edges and edge weights based on my matrix C; I started the following way:

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)

This plots a graph and there are labels on the vertices, but there are no edge weights - also I cannot adapt the technic from the upper link to make it work - so what could I do?

And how would I change node size and color?


Solution

  • There are various ways to do this using networkx - here is a solution which should fit your requirements:

    Code:

    # 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()
    

    Result:

    enter image description here