Search code examples
pythonmatplotlibplotnetworkxarrows

Why my code can't plot the arrow of a directed graph?


I've generated a directed graph with networkx.DiGraph(), but when I try to plot it, the arrows don't appear.

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_node(0, node_color="red")

G.add_node(1, node_color="orange")
G.add_node(2, node_color="orange")
G.add_node(3, node_color="orange")

G.add_node(4, node_color="yellow")
G.add_node(5, node_color="yellow")
G.add_node(6, node_color="yellow")
G.add_node(7, node_color="yellow")

G.add_edges_from([(0, 1),
                 (0, 2),
                 (0, 3),
                 (1, 4),
                 (2, 5),
                 (3, 6),
                 (3, 7)])

fig=plt.gcf()
fig.set_size_inches(100, 100)
ax=plt.gca()
pos=nx.circular_layout(G, center=(0, 0))
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), node_size = 5000)
nx.draw_networkx_edges(G, pos, arrows=True, arrowstyle = '-|>')

I expected a plt with arrows like this Expected

But my result is like this, there's no arrows on the edges: My result


Solution

  • Your node size is 5000 (the unit is square points, so I believe your circles are about an inch across) . This is probably needed because your plot is 100 inches by 100 inches (well over 2 meters by 2 meters)

    The default arrowhead size is 10 (which I believe in the units used for your arrowhead means it's about 4 points long and 2 points wide, or about .06 by .03 inches), so tiny in comparison.

    You've either got to increase the arrow size or decrease the node size and figure size. Here it is with just the default sizes for nodes, arrows and figures:

    import networkx as nx
    import matplotlib.pyplot as plt
    
    G = nx.DiGraph()
    G.add_node(0, node_color="red")
    
    G.add_node(1, node_color="orange")
    G.add_node(2, node_color="orange")
    G.add_node(3, node_color="orange")
    
    G.add_node(4, node_color="yellow")
    G.add_node(5, node_color="yellow")
    G.add_node(6, node_color="yellow")
    G.add_node(7, node_color="yellow")
    
    G.add_edges_from([(0, 1),
                     (0, 2),
                     (0, 3),
                     (1, 4),
                     (2, 5),
                     (3, 6),
                     (3, 7)])
    
    fig=plt.gcf()
    ax=plt.gca()
    pos=nx.circular_layout(G, center=(0, 0))
    nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'))
    nx.draw_networkx_edges(G, pos, arrows=True, arrowstyle = '-|>')
    

    enter image description here