networkx graph code example

Example 1: networkx display graph

import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge(1,2)
G.add_edge(1,3)
nx.draw(G, with_labels=True)
plt.show()

Example 2: networkx - add features from graph

df = pd.DataFrame(index=G.nodes())                              # Use nodes as index
df['node_name'] = pd.Series(nx.get_node_attributes(G, 'name'))  # Add attribute
df['clustering'] = pd.Series(nx.clustering(G))                  # Calculate lcc
df['degree'] = pd.Series(G.degree())                            # Calculate degree

Tags:

Misc Example