Networkx plot: Make edges stay out of the nodes

Question:

I want to plot a directional network graph using networkx in python. When using an alpha value different from 1 the beginnings of the edges are drawn also inside the nodes; the arrows are fine however.

How can I make the edges stay out of my nodes?

I didn’t find anything about it in the documentation. Setting alpha=1 would obviously solve it, but that is not what I want.

import math
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

pos={"x":(1/2, math.sqrt(3/4)), "y":(0,0), "z":(1,0)}

G=nx.DiGraph()
G.add_edge("x", "y")
G.add_edge("x", "z")
nx.draw(G, pos=pos, with_labels=True, node_size=1500, alpha=0.3, arrows=True,
        arrowsize=20, width=2)
plt.title("Direct link")
plt.show()

This is what comes out. The edges continue into the “x” node, which is bad.

enter image description here

Asked By: thorics

||

Answers:

You can solve this by drawing the nodes multiple times:

import math
import networkx as nx
import matplotlib.pyplot as plt

pos={"x":(1/2, math.sqrt(3/4)), "y":(0,0), "z":(1,0)}

G=nx.DiGraph()
G.add_edge("x", "y")
G.add_edge("x", "z")
nx.draw_networkx_edges(G, pos=pos, with_labels=True, node_size=1500, alpha=0.3, arrows=True,
        arrowsize=20, width=2)
# draw white circles over the lines
nx.draw_networkx_nodes(G, pos=pos, with_labels=True, node_size=1500, alpha=1, arrows=True,
        arrowsize=20, width=2, node_color='w')
# draw the nodes as desired
nx.draw_networkx_nodes(G, pos=pos, node_size=1500, alpha=.3, arrows=True,
        arrowsize=20, width=2)
nx.draw_networkx_labels(G, pos=pos)
plt.title("Direct link")
plt.axis("off")
plt.show()

Answered By: Sparky05

The draw_networkx_edges method has a parameter node_size that should help you position the edge outside of the node’s bounding box.

For example, this will result in the nodes covering the arrows because they’re too big:

G=nx.DiGraph()
G.add_edge("x", "y")
G.add_edge("x", "z")
pos = nx.spectral_layout(G)
nx.draw_networkx_edges(G, pos, arrows=True)
nx.draw_networkx_nodes(G, pos, node_size=1000)

arrows hidden

But it can be easily solved by informing the node_size during the rendering of the edges:

G=nx.DiGraph()
G.add_edge("x", "y")
G.add_edge("x", "z")
pos = nx.spectral_layout(G)
nx.draw_networkx_edges(G, pos, node_size=1000, arrows=True)
nx.draw_networkx_nodes(G, pos, node_size=1000)

arrows unhiden

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.