NetworkX is a python library for network/graph analysis. In the real world, the great example usage for network analysis is social network analysis (SNA), which is used for describing the relationship between peoples. Python is widely used for scientific and analysis purposes because there are so many packages that made for it, such as
scikit-learn, and for the specific field like network analysis, they have
networkx. I will show you how to get started with it and view the created graph using the
You have installed python on your machine, and could use the
pip to install these packages:
pip install --user networkx pip install --user matplotlib
or if you follow my previous posts about installing python using
pyenv and installing packages using
pipenv, you are welcome to use these commands because I prefer this way:
pipenv install networkx pipenv install matplotlib
Let's create two files within a folder for the simple demonstration project, the files are
miserables.json file contains graph data which you can get it from here.
- project |_ test.py |_ miserables.json
Now, let's code the
We will be using
matplotlib, and built-in package
json since we will deal with a JSON file.
import json import networkx as nx import matplotlib.pyplot as plt
We use the
json package to load the JSON file content and convert it into a dictionary object.
miserables_graph = None with open('miserables.json') as json_file: miserables_graph = json.load(json_file)
Then we create a networkx graph object or instance and add the nodes and edges from the previously imported dictionary object.
G = nx.Graph() G.add_nodes_from([(node['id'] for node in miserables_graph['nodes'])]) G.add_edges_from([(edge['source'], edge['target']) for edge in miserables_graph['links']])
And finally, show the graph using
You can run the
test.py file using
python test.py or
pipenv run python test.py if you're using
pipenv. When you run it, there will be a program instance spawn on your desktop.
You may find out the graph drawing is kind off and ugly 😆 I will find how to prettify it later but have fun exploring it yourself.