- 创建graph
#graph
from collections import OrderedDict
class Node:
def __init__(self,num):
self.num = num
self.adjacent = OrderedDict()
class Graph:
def __init__(self):
self.nodes = OrderedDict()
def add_node(self,num):
node = Node(num)
self.nodes[num] = node
return node
def add_edge(self,source,dest,weight=0):
if source not in self.nodes:
self.add_node(source)
if dest not in self.nodes:
self.add_node(dest)
self.nodes[source].adjacent[self.nodes[dest]] = weight
2. “图”的快速生成可视化
data = """
Cognite AkerBP
ESA Kalkulo NTNU AkerBP
Dig RSI Imperial Equinor DEA Eni Emerson
DTU UiB SLB DEA NPD
Emerson Kadme COP Accenture
Equinor CRC XOM Cegal
Equinor SLB UiB Cegal
COP Cegal AkerBP
COP CapGemini
"""
p = {
"Cognite": 4,
"AkerBP": 3,
"ESA": 3,
"Kalkulo": 1,
"NTNU": 1,
"Dig": 1,
"RSI": 1,
"Imperial": 1,
"Equinor": 6,
"DEA": 2,
"Eni": 1,
"Emerson": 2,
"DTU": 1,
"UiB": 2,
"NPD": 1,
"Kadme": 1,
"COP": 5,
"Accenture": 1,
"CRC": 1,
"XOM": 1,
"Cegal": 5,
"SLB": 2,
"CapGemini": 5
}
t = {
'Accenture': 2,
'AkerBP': 1,
'COP': 1,
'CRC': 1,
'CapGemini': 2,
'Cegal': 2,
'Cognite': 2,
'DEA': 1,
'DTU': 3,
'Dig': 2,
'ESA': 2,
'Emerson': 2,
'Eni': 1,
'Equinor': 1,
'Imperial': 3,
'Kadme': 2,
'Kalkulo': 2,
'NPD': 0,
'NTNU': 3,
'RSI': 2,
'SLB': 2,
'UiB': 3,
'XOM': 1
}
colours = {
0: 'lightgreen',
1: 'turquoise',
2: 'pink',
3: 'deepskyblue'
}
# Type of organization: 0 for government, 1 for operator, 2 for service, 3 for academic.
tmp = [list(d.split('\t')) for d in data.split('\n')]
tmp
tmp = [list(filter(None,d.split('\t'))) for d in data.split('\n')]
tmp
del tmp[0]
del tmp[-1]
tmp
data = tmp
from itertools import combinations
edges = []
for d in data:
combs = combinations(d,2)
edges += list(combs)
edges
以上是部分截图
len(edges)
60
import networkx as nx
G = nx.Graph()
G.add_edges_from(edges)
import matplotlib.pyplot as plt
%matplotlib inline
fig,ax = plt.subplots(figsize=(16,8))
nx.draw(G,with_labels=True)
t = {k:t[k] for k in list(p.keys())}
node_color = [colours[n] for n in t.values()]
node_color
nx.set_node_attributes(G,p,'participants')
nx.set_node_attributes(G,t,'sector')
import numpy as np
fig,ax = plt.subplots(figsize=(16,8))
nx.draw(G,with_labels=True,edge_color='lightgray',node_color=[colours[n] for n in t.values()],\
nodelist = list(p.keys()),node_size=400*np.array(list(p.values())))
pos = nx.kamada_kawai_layout(G)
fig,ax = plt.subplots(figsize=(16,8))
nx.draw(G,with_labels=True,edge_color='lightgray',node_color=[colours[n] for n in t.values()],\
nodelist = list(p.keys()),node_size=400*np.array(list(p.values())))
pos = nx.spring_layout(G)
fig,ax = plt.subplots(figsize=(16,8))
nx.draw(G,with_labels=True,edge_color='lightgray',node_color=[colours[n] for n in t.values()],\
nodelist = list(p.keys()),node_size=400*np.array(list(p.values())))