NetworkX Visualization

Customizing a plot: Example-1

In the following self-contained example we show how to add various customization options to a plot

import networkx as nx
import matplotlib.pyplot as plt

#GENERATE GRAPH
G = nx.complete_graph(5)

#BASIC PLOT
nx.draw(G)
plt.show()

#CUSTOMIZE
#specifiy x-y positions for plotting
pos=nx.circular_layout(G)

#initialize plot
fig, ax = plt.subplots()
nx.draw(
G,
node_color='blue',
edgecolors="black",
edge_color="black", 
linewidths=2,
font_color="white",
font_weight="bold",
node_size=500,
width=2,
with_labels=True,
pos=pos,
ax=ax
)
ax.set(title='Basic NetworkX plot')
ax.set_aspect('equal', 'box')
#fig.savefig("test.png")
plt.show()

Customizing a plot: Example-2

In the following self-contained example we show how to add various customization options to a NetworkX plot

import networkx as nx
import matplotlib.pyplot as plt
import random
import numpy as np

#GENERATE GRAPH
N=20

G = nx.complete_graph(N)
G = nx.gnp_random_graph(N, 0.1, seed=10374196)

#ASSIGN RANDOM ATTRIBUTES TO NODES+EDGES
for u in G.nodes(): G.nodes[u]['attribute']=0.2+1*random.uniform(0, 1) 
for u,v in G.edges(): G[u][v]['weight']=5*random.uniform(0, 1) 

#PRINT NODE+EDGES
for node in G.nodes(data=True): print(node)
for line in nx.generate_edgelist(G, data=True): print(line)

#SPECIFIY X-Y POSITIONS FOR PLOTTING
# pos=nx.circular_layout(G)
pos=nx.spring_layout(G,k=50*1./np.sqrt(N),iterations=500)
# pos=nx.random_layout(G)

#GENERATE PLOT
fig, ax = plt.subplots()
fig.set_size_inches(10, 10)

#assign colors based on attributes
weights_n   = [G.nodes[u]['attribute'] for u in G.nodes()]
weights_e   = [G[u][v]['weight'] for u,v in G.edges()]

#SAMPLE CMAP FOR COLORS 
cmap=plt.cm.get_cmap('Blues')
colors_e    = [cmap(G[u][v]['weight']/5.0) for u,v in G.edges()]
colors_n    = [cmap(G.nodes[u]['attribute']/1.2) for u in G.nodes()]

#VARIOUS METHODS FOR VISUALIZING SIZE

#LABELS (DICT)
labels={}
for n,d in nx.degree(G): labels[n]=d #str(n)+"-"+str(d) 

#WEIGHTS
# node_size=1000*weights_n

#DEGREE CENTRALITY
centrality=nx.degree(G)
centrality=np.array([d for n,d in centrality]); #print(G_DEGREE)
node_size=1000*centrality/max(centrality)
colors_n = node_size
colors_n = [cmap(u/max(centrality)) for u in centrality]

#PLOT
nx.draw(
G,
    node_color=colors_n,
    edgecolors="black",
    edge_color=colors_e,
    linewidths=2,
    labels=labels,
    font_color="white",
    font_weight="bold",
    node_size=node_size, 
    width=weights_e,
    with_labels=True,
    pos=pos,
    ax=ax
)

#TITLE 
ax.set(title='Color and size plotted by attribute')
ax.set_aspect('equal', 'box')

#PLOT
# fig.savefig("test.png")
plt.show()
(0, {'attribute': 0.8432192906708564})
(1, {'attribute': 0.9003084050173153})
(2, {'attribute': 0.36227567432024804})
(3, {'attribute': 0.5530535380037791})
(4, {'attribute': 0.3885993353669905})
(5, {'attribute': 0.9271636734518809})
(6, {'attribute': 0.8787046418607791})
(7, {'attribute': 0.5381855380228355})
(8, {'attribute': 0.8909451269189954})
(9, {'attribute': 1.028742658296936})
(10, {'attribute': 0.7750714278728279})
(11, {'attribute': 0.5702427334174116})
(12, {'attribute': 0.9827879047975148})
(13, {'attribute': 1.0641809756299672})
(14, {'attribute': 0.9376297923204349})
(15, {'attribute': 1.1943948586555406})
(16, {'attribute': 1.0264215738685571})
(17, {'attribute': 0.7383645022100458})
(18, {'attribute': 0.6813542737452929})
(19, {'attribute': 0.604351736830669})
0 14 {'weight': 4.731096967245605}
1 14 {'weight': 4.239763887003179}
2 9 {'weight': 1.3349281589796125}
2 11 {'weight': 2.449076914199649}
3 9 {'weight': 3.620604945528804}
3 12 {'weight': 0.5213283930635743}
4 11 {'weight': 2.558547773090627}
4 12 {'weight': 1.260855154487262}
4 15 {'weight': 4.875199479685817}
5 12 {'weight': 3.7938668683697463}
5 13 {'weight': 3.4899420854486123}
5 15 {'weight': 1.5326001966345115}
5 17 {'weight': 0.8614405877011111}
6 19 {'weight': 0.4857162186912406}
7 14 {'weight': 4.5351940394041454}
7 18 {'weight': 2.0691919285951483}
8 9 {'weight': 3.790431618707273}
8 17 {'weight': 0.9996778144800522}
10 13 {'weight': 4.279762308461165}
10 17 {'weight': 3.9283682425949613}
10 18 {'weight': 1.8661995203432795}
11 13 {'weight': 3.6364799154302645}
12 19 {'weight': 0.6511208450509864}
13 15 {'weight': 3.5705554357556597}
13 18 {'weight': 2.444773150968586}
14 15 {'weight': 1.1807366251576723}
/var/folders/lc/n91cn5z96ws6f52d25t2rpbh0000gn/T/ipykernel_30774/2235291110.py:34: MatplotlibDeprecationWarning: The get_cmap function was deprecated in Matplotlib 3.7 and will be removed in 3.11. Use ``matplotlib.colormaps[name]`` or ``matplotlib.colormaps.get_cmap()`` or ``pyplot.get_cmap()`` instead.
  cmap=plt.cm.get_cmap('Blues')

Node degree histogram

  • A node degree histogram is a graphical representation of the frequency distribution of the degrees of nodes in a network.
  • The x-axis shows the node degrees, and the y-axis displays the number of nodes with that degree.
  • It helps visualize the connectivity pattern of a network, such as the presence of hubs or the degree distribution.
# MODIFIED FROM 
# https://networkx.org/documentation/stable/auto_examples/drawing/plot_degree.html
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

#-------------------
# PLOTTING FUNCTION
#-------------------
def degree_histogram_plot(G):
    #COMPUTE DEGREE: --> "LIST" WITH NODE DEGREES
    G_DEGREE=G.degree(); #print(G_DEGREE,G_DEGREE[5],type(G_DEGREE)) 

    #LABELS (DICT)
    labels={}
    for n,d in G_DEGREE: labels[n]=d #str(n)+"-"+str(d) 

    #SORT DEGREE AND STORE IN LIST 
    degree_sequence = sorted((d for n, d in G_DEGREE), reverse=True)
    dmax = max(degree_sequence)   #MAX DEGREE

    #INITIALIZE MPL FIGURE+AX
    fig = plt.figure("Degree of a random graph", figsize=(10, 10))
    # Create a gridspec for adding subplots of different sizes
    axgrid = fig.add_gridspec(5, 4)

    #PLOT NETWORK IN UPPER GRID SPACES 
    ax0 = fig.add_subplot(axgrid[0:3, :])
    pos = nx.spring_layout(G)
    nx.draw(G,
        with_labels=True,
        labels=labels,
        node_color='blue',
        node_size=500,
        font_color='white',
        font_size=16,
        pos=pos,ax=ax0
        )
    ax0.set_title("Network Graph: G")

    #PLOT RANK (IMPORTANCE BASED ON DEGREE) VS DEGREE)
    ax1 = fig.add_subplot(axgrid[3:, :2])
    ax1.plot(degree_sequence, "b-", marker="o")
    ax1.set_title("Degree Rank Plot")
    ax1.set_ylabel("Degree")
    ax1.set_xlabel("Rank")

    #PLOT RANK HISTOGRAM
    ax2 = fig.add_subplot(axgrid[3:, 2:])
    ax2.bar(*np.unique(degree_sequence, return_counts=True))
    ax2.set_title("Degree histogram")
    ax2.set_xlabel("Degree")
    ax2.set_ylabel("# of Nodes")
    ax0.set_aspect('equal', 'box')
    fig.tight_layout()
    plt.show()

    print(
    "NETWORK DENSITY:", nx.density(G), "\n",
    "NETWORK DIAMETER:", nx.diameter(G), "\n",
    )

#-------------------
#GENERATE GRAPHS+PLOT
#-------------------
print("RANDOM GRAPH")
#gnp_random_graph(n, p=, seed=None, directed=False)
#p=connection probablity
G = nx.gnp_random_graph(100, 0.2, seed=10374196)
degree_histogram_plot(G)

print("COMPLETE GRAPH")
G = nx.complete_graph(50)
degree_histogram_plot(G)

print("BINOMIAL TREE")
G = nx.binomial_tree(7)
degree_histogram_plot(G)
RANDOM GRAPH

NETWORK DENSITY: 0.20646464646464646 
 NETWORK DIAMETER: 3 

COMPLETE GRAPH

NETWORK DENSITY: 1.0 
 NETWORK DIAMETER: 1 

BINOMIAL TREE

NETWORK DENSITY: 0.015625 
 NETWORK DIAMETER: 13 

Graph Layouts

  • A graph visualization layout arranges nodes and edges in a visually intuitive manner.
  • Examples include hierarchical trees with parent-child relationships, force-directed layouts where nodes repel each other, and circular layouts that arrange nodes in a circle.
  • In the following example the code explores various Network-X positional layouts
import networkx as nx
import matplotlib.pyplot as plt

#GENERATE A COMPLETE GRAPH USING A GRAPH GENERATOR 
#https://networkx.org/documentation/stable/reference/generators.html
# G = nx.complete_graph(10)
G = nx.gnp_random_graph(10,p=0.7)
for i in range(1,7+1):
    #print(i)
    #CAN MANUALLY SPECIFY GRAPH LOCATIONS WITH A DICTIONARY OF (X,Y) ARRAYS 
    if(i==1): 
        title="Layout: Manual"; pos={}; j=0; i1=0
        for k in range(0,len(list(G.edges))):
            if(k%5==0): j=j+1
            if(k%5==0): i1=0
            i1=i1+1
            pos[k]=[j,i1]

    # OR YOU CAN USE ONE OF NETWORK-X'S BUILT-IN POSITION LAYOUT ALGORITHMS
    if(i==2): title="Layout: Spectral";     pos = nx.spectral_layout(G)
    if(i==3): title="Layout: Circular";     pos = nx.circular_layout(G)
    # if(i==4): title="Layout: Kamada-Kawai"; pos = nx.kamada_kawai_layout(G)
    if(i==5): title="Layout: Random";       pos = nx.random_layout(G)
    if(i==6): title="Layout: Shell";        pos = nx.shell_layout(G)
    if(i==7): title="Layout: Spring";       pos = nx.spring_layout(G,iterations=200)


    fig, ax = plt.subplots()
    fig.set_size_inches(6, 6)

    nx.draw(
        G,
        node_color="blue",
        node_size=500,
        font_color="white",
        font_weight="bold",
        with_labels=True,
        pos=pos,
    )
    ax.set(title=title)
    # if(i>1): ax.set_aspect('equal', 'box')
    plt.title(title)
    plt.show()