## Network x + Python constructs graph structure data and visualizes it

Wooden calyx 2020-11-13 08:47:37
network python constructs graph structure

At present, the most common way to deal with non European data is to build chart , and networkx A special tool for building graph data . It's easy to use .

Give the link first ：https://networkx.github.io/

Official documents https://networkx.github.io/documentation/latest/

networkx The official document above has been recorded in detail , Ah Zhan doesn't have to repeat .

There are several in the official documents demo, Although convenient , But the generalization is not strong . I'll give you a more general demo：

import networkx as nx
import matplotlib.pyplot as plt
g = nx.Graph()
fig, ax = plt.subplots()
nx.draw(g, ax=ax)
plt.show()

The graph data we build is g, I can see that there are ['1', '2', '3', 4''] Four nodes . The visualization result is ：

It's just a picture of a bare stick , You can put nodes label add , Just set up with_labels=True:

import networkx as nx
import matplotlib.pyplot as plt
g = nx.Graph()
fig, ax = plt.subplots()
nx.draw(g, ax=ax, with_labels=True) # show node label
plt.show()

Have you found every Visualization , The positions of the nodes in the graph are randomly placed . If you want to fix the position of the node , It's OK, too ：

import networkx as nx
import matplotlib.pyplot as plt
g = nx.Graph()
pos_dict = {'1':[ 1, 1], '2': [ 1.5, 0.8], '3': [ 1.7, 2.8], '4': [ 0.6,3.3]}
positions=nx.spring_layout(G, pos=pos_dict)
fig, ax = plt.subplots()
nx.draw(g, ax=ax, with_labels=True, pos=positions)
plt.show()

Enter the coordinates of each node in the visualization as above , You can fix the node in one place . such , No matter how many times , The visualization result will only be one appearance ：

It's not handsome enough , If I want to use Different colors To show the nodes ？

import networkx as nx
import matplotlib.pyplot as plt
g = nx.Graph()
fixed_position = {'1':[ 1, 1], '2': [ 1.5, 0.8], '3': [ 1.7, 2.8], '4': [ 0.6,3.3]}
pos=nx.spring_layout(g, pos=fixed_position)
colors = []
for i in range(g.number_of_nodes()):
if i == 2:
colors.append('#ff0000')
else:
colors.append('#1f7814')
fig, ax = plt.subplots()
nx.draw(g, ax=ax, with_labels=True, pos=pos, node_color=colors) # add colors
plt.show()

It's nothing but adding another colors Of list, Let's see the effect :

Because the last step must have fixed the node , therefore , This step only adds color show The shape of the graph is the same as that of the next step .

It should be noted that ,colors It's just list, Not bound to every node , It's just binding in order . The order of nodes is in networkx It's first in, first out , For example, you first add_edge('1', '3') Again add_edge('1', '2'), This is the time '2' It's the third node , and '2' It's just the third node label.

To solve the problem of sequence correspondence , You can start with add_node.