1. 特色二部图
修改节点与边颜色、大小等
import networkx as nx
import matplotlib.pyplot as plt
plt.figure('设备-用户关系图', figsize=(4, 6)) # 设置画布大小
list_fid = [1, 2, 3, 4] # 添加设备节点
list_uid = ["a", "b", "c"] # 添加用户节点
edges = [(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")] # 添加关系
# --------- 在图中添加节点与边 ---------
B = nx.Graph()
B.add_nodes_from(list_fid, bipartite=0)
B.add_nodes_from(list_uid, bipartite=1)
B.add_edges_from(edges)
# --------- 设定坐标 画节点 ---------
pos_fid = dict((n, (1, i*1.18)) for i, n in enumerate(list_fid)) # 可通过乘系数,调整节点分布
pos_uid = dict((n, (2, i*1.58)) for i, n in enumerate(list_uid))
nx.draw_networkx_nodes(G=B, pos=pos_fid, nodelist=list_fid, node_size=300, node_color='red', margins=0.001)
nx.draw_networkx_nodes(G=B, pos=pos_uid, nodelist=list_uid, node_size=300, node_color='blue', margins=0.001)
# --------- 设定坐标 画节边 ---------
pos = {} # 全部节点坐标
pos.update(pos_fid)
pos.update(pos_uid)
nx.draw_networkx_edges(B, pos, edges)
# --------- 画节点标签 ---------
labels_fid = dict(zip(list_fid, list_fid)) # 节点对应的标签
labels_uid = dict(zip(list_uid, list_uid)) # 节点对应的标签
nx.draw_networkx_labels(B, pos=pos_fid, labels=labels_fid, font_size=12.5) # 画标签
nx.draw_networkx_labels(B, pos=pos_uid, labels=labels_uid, font_size=12.5) # 画标签
# --------- 保存图片 ---------
plt.savefig("relation1.png", dpi=120)
plt.show()
如下:
从文件获取节点和边数据源
# 获得 fid-uid 关系
def get_uid_fid_relation():
df = pd.read_csv('data/uid_fid.csv', dtype=str)
relation_uid_fid_list = []
for line in df.values:
relation_uid_fid_list.append((line[0], line[1]))
return relation_uid_fid_list
# 获得设备节点
def get_fid_node_list():
df = pd.read_csv('data/fid.csv', dtype=str)
list_fid = df['fid'].to_list()
return list_fid
# 获得用户节点
def get_uid_node_list():
# df = pd.read_csv('data/uid.csv', header=0, names=['user_id'], dtype=str)
df = pd.read_csv('data/uid.csv', dtype=str)
list_uid = df['user_id'].to_list()
return list_uid
if __name__ == '__main__':
list_fid = get_fid_node_list() # 设备节点
list_uid = get_uid_node_list() # 用户节点
edges = get_uid_fid_relation() # 关系
11