forward: https://martinlwx.github.io/en/how-to-draw-a-simple-relation-graph-in-python/
Intro
The process of drawing a simple relation graph in python can be broken down into 2 steps.
- Define a graph.
- Draw a graph.
Step 1. Define a graph
In this step, we will use the networkx package.
Install tutorial
If you are using conda, you can just type conda install networkx
If you are using pip, you can just type pip install networkx
Nodes
First of all, you need to create a graph.
import networkx as nx
G = nx.Graph()
You can use different ways to add nodes.
- Add one node at a time.
- Add nodes from any iterable container
- Add nodes along with node attributes. In this way, you can define many attributes of a node, such as color, size, etc.
- Add nodes from another graph directly
G.add_node(1) # method 1
G.add_nodes_from([2, 3, 4, 5]) # method 2
G.add_nodes_from([ # method 3
(6, {"color": "red"}),
(7, {"color": "blue"})
])
G2 = nx.Graph() # method 4
G2.add_nodes_from([8, 9, 10])
G.add_nodes_from(G2)
# you can verify nodes by
print(G.nodes)
# NodeView((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
Edges
Also, networkx
has many ways to add edges, which is quite similar to add nodes. Let’s just jump to the code