반응형

/*******************************************************************************************************************
-- Title : [Py3.5] NetworkX Example (w/ Family Data)
-- Key word : networkx network-x 네트워크 차트 chart 그래프 graph 노드 엣지 node edge 
*******************************************************************************************************************/

■ Figures



■ Scripts (on Jupyter Notebook)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# coding: utf-8
 
# In[1]:
 
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
 
df1 = pd.DataFrame(columns=['skey','seq','no'])
df1.skey = ['111','222','222','222','333','333','333','444','444','444','555']
df1.seq = [1,1,2,3,1,2,3,1,2,3,1]
df1.no = ['A','A','B','C','A','B','D','C','D','E','E']
df1
 
 
# In[2]:
 
df2 = pd.DataFrame(columns=df1.no.unique(),index=df1.skey.unique())
for i, [skey,seq,no] in df1.iterrows():
    df2.loc[skey,no] = 1
df2 = df2.fillna(0)
df2
 
 
# In[3]:
 
skeys = list(df2.index.get_values())
columns = list(df2.columns.get_values())
print(skeys)
print(columns)
edges = []
for skey,*arg in df2.itertuples():
    for i,con in enumerate(arg):
        if con:
            edges.append((skey, df2.columns[i]))
edges
 
 
# In[4]:
 
get_ipython().magic('time')
G1 = nx.Graph()
G1.add_edges_from( edges )
 
def circular_pos(n, r):
    pos = []
    pos.append((0,r))
    th = 2*np.pi/n
    for i in range(n-1):
        x = np.cos(th)*pos[i][0]-np.sin(th)*pos[i][1]
        y = np.sin(th)*pos[i][0]+np.cos(th)*pos[i][1]
        pos.append((x,y))
    return pos
 
skey_pos = {skey:pos for skey,pos in zip(skeys,circular_pos(len(skeys), 2))}
col_pos = {col:pos for col,pos in zip(columns,circular_pos(len(columns), 1))}
pos = {}
pos.update(skey_pos)
pos.update(col_pos)
 
labels = {n:n for n in G1.nodes()}
 
nx.draw_networkx_nodes(G1, pos, nodelist=skeys[:2], node_size=1000, node_color='lightgreen')
nx.draw_networkx_nodes(G1, pos, nodelist=skeys[2:], node_size=1000, node_color='lightblue')
nx.draw_networkx_nodes(G1, pos, nodelist=columns, node_color='yellow')
nx.draw_networkx_edges(G1, pos=pos, alpha=0.5, width=2)
nx.draw_networkx_labels(G1, pos, labels, font_size=10)
 
plt.axis('off')
plt.show()
 
 
# In[5]:
 
df2
 
 
# In[6]:
 
from itertools import combinations
 
G2 = nx.Graph()
 
for col in columns:
    tmp = df2[df2[col] == True].index.values.tolist()
    edges = list(combinations(tmp, 2))
 
    G2.add_edges_from(edges)
    
nx.draw_networkx(G2, font_size=10, node_color='lightblue', node_size=800)
plt.axis('off')
plt.show()
cs



반응형

+ Recent posts