Manipulating Graphs with NetworkX
NetworkX is a powerful pure-Python library for creating, manipulating, and analyzing graphs. This guide covers essential tasks using NetworkX.
Inspecting Directed Graphs: In-Edges and Out-Edges
For directed graphs (nx.DiGraph), you may want to know which edges point into or out of a node.
Example:
1 | |
G.in_edges(node)returns edges directed intonodeG.out_edges(node)returns edges directed out ofnode
Visualizing Graphs with PyGraphviz and Graphviz
NetworkX can interface directly with PyGraphviz and Graphviz, popular software packages for graph visualization.
Installing Graphviz and PyGraphviz
Before you can use these visualization features, you need to install both PyGraphviz and Graphviz. On most systems, the easiest way is:
1 | |
Rendering Graphs as Images
Once you have everything installed, you can easily convert a NetworkX graph into a Graphviz object and save it directly as an image (PNG, PDF, etc.):
1 | |
nx.nx_agraph.to_agraph(G)converts your NetworkX graph to a PyGraphviz (Graphviz) AGraph object..write("G.dot")saves the graph in DOT format (plain text for Graphviz)..draw("G.png", prog="dot")renders the image using the Graphviz “dot” layout engine.
You can open G.png in any image viewer to see the visualization.
Tip: Try changing the
progargument to other Graphviz layout engines like"neato"or"fdp"for different layouts.
Further Customization
You can customize node shapes, colors, and more using AGraph’s methods or by passing attributes on creation; see the pygraphviz documentation for more details.
Serializing and Deserializing Graphs
When working with graphs, you may want to save (serialize) them to a file and load (deserialize) them later. There are two common approaches in NetworkX:
A. Using JSON (Node-Link Data)
Why?
- Human-readable
- Cross-language interoperability
Serialize to JSON:
1 | |
Deserialize from JSON:
1 | |
Tip: JSON is a popular serialization format and can be easily used with web apps or other languages.
B. Using Pickle
Why?
- Fastest method in Python
- Carries all Python-specific information
- Warning: Not safe for untrusted data, and not interoperable with other languages.
Serialize using Pickle:
1 | |
Deserialize using Pickle:
1 | |