Search code examples
pythonmatplotlibnetwork-programmingnetworkx

How to create arrow in this ego network?


import networkx as nx

import matplotlib.pyplot as plt

G = nx.Graph()

G.add_edges_from([('A', 'B'), ('A', 'C'),
                  ('B', 'C'), ('E', 'F'),
                  ('D', 'E'), ('A', 'D'),
                  ('D', 'C'), ('C', 'F'),
                  ('D', 'E')])

ego = 'A'

pos = nx.spring_layout(G)

nx.draw(G, pos, node_color="lavender",
        node_size=800, with_labels=True)

options = {"node_size": 1200, "node_color": "r"}

nx.draw_networkx_nodes(G, pos, nodelist=[ego], **options)

plt.show()

`

I want to create arrows for the ego networks. I want it like this. This is my current output

I did not try anything cause I do not know how to add arrows.


Solution

  • To show arrows you might define: arrows=True and arrowstyle

    UPDATE: the edges must be rearranged to match the draft you put here https://i.sstatic.net/zfo6F.jpg

    import networkx as nx
    
    import matplotlib.pyplot as plt
    
    G = nx.Graph()
    
    G.add_edges_from([('A', 'B'), ('A', 'C'),('A', 'D'),
                      ('B', 'C'), 
                      ('C', 'D'), ('C', 'F'),
                      ('D', 'E'),
                      ('F', 'E')])
    
    ego = 'A'
    
    pos = nx.spring_layout(G)
    
    nx.draw(G, pos, node_color="lavender",
            arrows=True, arrowstyle='-|>',    #   <-- Add this one
            node_size=800, with_labels=True)
    
    options = {"node_size": 1200, "node_color": "r"}
    
    nx.draw_networkx_nodes(G, pos, nodelist=[ego], **options)
    
    plt.show()
    

    Result:

    enter image description here