In the following self-contained example we show how to add various customization options to a plot
import networkx as nximport matplotlib.pyplot as plt#GENERATE GRAPHG = nx.complete_graph(5)#BASIC PLOTnx.draw(G)plt.show()#CUSTOMIZE#specifiy x-y positions for plottingpos=nx.circular_layout(G)#initialize plotfig, 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 nximport matplotlib.pyplot as pltimport randomimport numpy as np#GENERATE GRAPHN=20G = nx.complete_graph(N)G = nx.gnp_random_graph(N, 0.1, seed=10374196)#ASSIGN RANDOM ATTRIBUTES TO NODES+EDGESfor 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+EDGESfor 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 PLOTfig, ax = plt.subplots()fig.set_size_inches(10, 10)#assign colors based on attributesweights_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 CENTRALITYcentrality=nx.degree(G)centrality=np.array([d for n,d in centrality]);#print(G_DEGREE)node_size=1000*centrality/max(centrality)colors_n = node_sizecolors_n = [cmap(u/max(centrality)) for u in centrality]#PLOTnx.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()
/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.htmlimport networkx as nximport numpy as npimport 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 probablityG = 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)
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 nximport 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 inrange(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=0for k inrange(0,len(list(G.edges))):if(k%5==0): j=j+1if(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 ALGORITHMSif(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()