Search code examples
pythonnetworkx

How to add arrows on Networkx graph


I have made a graph with networkx lib in Python. Now I want to add arrows on the lines on the graph, but It seams that I am doing something wrong. This is my code:

import networkx as nx

analysis_graph = nx.Graph()
# I have also tried with DiGraph() but it still does not work

node_list = ["A", "B", "C", "D", "E", "F"]

analysis_graph.add_nodes_from(node_list)
#print(analysis_graph.nodes())

nx.draw(analysis_graph, with_labels = True)
relation_list = [['A', 'B'],
                 ['A', 'C'],
                 ['B', 'D'],
                 ['C', 'E'],
                 ['D', 'F'],
                 ['E', 'D'],
                 ['C', 'E'],
                 ['B', 'D'],                 
                 ['C', 'F'],
                 ['A', 'E'],
                 ['B', 'C'],                 
                 ['B', 'F'],
                 ['D', 'A']]

analysis_graph = nx.from_edgelist(relation_list)
print(nx.info(analysis_graph))
nx.draw(analysis_graph, with_labels = True, arrowsize=20, arrowstyle='fancy')

What am I doing wrong?


Solution

  • To draw arrows, the graph apparently does have to be a DiGraph object. If I change the following line:

    analysis_graph = nx.from_edgelist(relation_list)
    

    to

    analysis_graph = nx.from_edgelist(relation_list, create_using=nx.DiGraph)
    

    I do get the desired output.

    enter image description here

    Your previous attempt to instantiate a DiGraph object in line 2 (ignoring blanks)

    analysis_graph = nx.DiGraph()
    

    had no effect, as you are overwriting the analysis_graph object when calling nx.from_edgelist. What you probably meant to write was

    analysis_graph = nx.DiGraph()
    analysis_graph.add_nodes_from(nodelist)
    analysis_graph.add_edges_from(relation_list)