Create interconnected systems and easy-to-navigate networks from dataframes and Excel files
NetworkX enables users to model and analyze complex structures and multi-layered networks
Official documentation for NetworkX is available online at networkx.org
To utilize the visualization capabilities of NetworkX, you will need to have Matplotlib installed and imported.
NetworkX requires Python 3.11 or greater.
Install package:
pip install networkxImport library:
import networkx as nxGraph: undirected graph with only one edge between nodes (example):
graph = nx.Graph()Multigraph: undirected graph with multiple edges between nodes (example):
multigraph = nx.Multigraph()Digraph: directed graph with only one edge between nodes (example):
digraph = nx.Digraph()Multidigraph: directed graph with multiple edges between nodes(example):
multidigraph = nx.MultiDigraph()df = pd.read_csv('social_network.csv')
df# social_network.csv
| username | first_follower | days |
| john_blackwell | yang_jeongin | 29 |
| yang_jeongin | john_blackwell | 143 |
| winter_maddox | john_blackwell | 47 |# Initialize variable containing csv data
graph = nx.from_pandas_edgelist(df, source = 'username', target = 'first_follower', edge_attr = 'days')
# Retrieve all node names
graph.nodes()RESULT:
NodeView(("john_blackwell", "yang_jeongin", "winter_maddox"))
Make relatedness of nodes more apparent:
layout = nx.spring_layout(graph)Visualize:
nx.draw_networkx_nodes(graph, layout)
nx.draw_networkx_edges(graph, layout)
nx.draw_networkx_labels(graph, layout)
plt.show()Change node size:
# Change `node_size` for increasing/decreasing size of nodes
nx.draw_networkx_nodes(graph, layout, node_size = 500)Change node color:
# Change `alpha` for color
nx.draw_networkx_edges(graph, layout, alpha = 0.5)Change edge thickness:
# Edge weight dependent on 'days' column data
weight = list(nx.get_edge_attributes(graph, 'days').values())
# Add weight to lines connecting nodes
nx.draw_networkx_edges(graph, layout, width = weight)Feel free to let me know of any errors or bugs you find! Also, if you need help for a specific project of yours using NetworkX, open an issue or send me a pull request!