Display variable sized circles on top of nodes in NetworkX

Viewed 157

I have a weighted networkx graph. I've computed the eigenvector centrality values on the graph; however, I wanted to also add circles ontop of each node that visually represent the eigenvector value of the particular node. The circles would differ in size depending on the eigenvector value of the respective node. (the greater the value, the bigger the circle ontop of the node).

I'm using the following code:

import networkx as nx

# Create a random graph
G = nx.gnp_random_graph(20, 0.2)

# Calculate centrality
centrality = nx.eigenvector_centrality_numpy(G)

# Create labels dict with fixed digit format
labels = {
    node: '{:.3f}'.format(centrality[node])
    for node in centrality
}

# Draw the graph with labels
nx.draw(
    G,
    with_labels=True,
    labels=labels,
    node_color='#FF0000'
)
1 Answers

You could get what you want both with matplotlib.pyplot.text and matplotlib.pyplot.Circle. You might want to adjust slightly differently, but hopefully this serves as a good starting point:

import networkx as nx

# Create a random graph
G = nx.gnp_random_graph(20, 0.2)

# Calculate centrality
centrality = nx.eigenvector_centrality_numpy(G)

# Create labels dict with fixed digit format
labels = {
    node: '{:.3f}'.format(centrality[node])
    for node in centrality
}

plt.figure(figsize=(20,20))
ax = plt.gca()
ax.set_aspect('equal')

pos = nx.spring_layout(G)
nx.draw(G, 
        pos=pos,
        node_color='lightblue', 
        labels=labels,
        with_labels=True)

for node, (x,y) in pos.items():
    rad = centrality[node]*0.16
    circle = plt.Circle((x,y+rad), radius=rad, color='orange')
    plt.text(x-.012, y+rad, node, fontsize=16, weight="bold")
    ax.add_artist(circle)
    
plt.show()

enter image description here

Related