如何在Python中使用igraph或networkx基于字典数据绘制关系图
实现方案
以下分别提供networkx和igraph两种库的实现代码,默认构建「标题-标签」二部关系图,你可以根据需求调整节点样式、布局规则。
方案1:使用networkx实现
需要提前安装依赖:pip install networkx matplotlib
完整代码如下:
import networkx as nx import matplotlib.pyplot as plt # 你的源数据 my_data = [ { 'title': 'title1', 'tags': ['tag1', 'tag2', 'tag3'] }, { 'title': 'title2', 'tags': ['tag1'] } ] # 初始化无向图 G = nx.Graph() # 遍历数据添加节点和边 for item in my_data: title = item['title'] # 给标题节点加类型标记 G.add_node(title, node_type='title') for tag in item['tags']: # 给标签节点加类型标记 G.add_node(tag, node_type='tag') # 建立标题和标签的关联边 G.add_edge(title, tag) # 按节点类型分配颜色,标题为蓝色,标签为橙色 color_map = [] for node_attr in G.nodes(data=True): if node_attr[1]['node_type'] == 'title': color_map.append('#4287f5') else: color_map.append('#f5a742') # 绘制图形 pos = nx.spring_layout(G, seed=42) # 固定随机种子保证布局可复现 nx.draw( G, pos, node_color=color_map, with_labels=True, node_size=1500, font_size=10, font_color='white' ) plt.show()
方案2:使用igraph实现
需要提前安装依赖:pip install igraph
完整代码如下:
import igraph as ig # 你的源数据 my_data = [ { 'title': 'title1', 'tags': ['tag1', 'tag2', 'tag3'] }, { 'title': 'title2', 'tags': ['tag1'] } ] edges = [] node_type_map = {} # 预处理生成边列表和节点类型映射 for item in my_data: title = item['title'] node_type_map[title] = 'title' for tag in item['tags']: node_type_map[tag] = 'tag' edges.append((title, tag)) # 初始化图并添加节点、边 g = ig.Graph() g.add_vertices(list(node_type_map.keys())) g.add_edges(edges) # 配置节点属性 g.vs['type'] = [node_type_map[name] for name in g.vs['name']] g.vs['color'] = ['#4287f5' if t == 'title' else '#f5a742' for t in g.vs['type']] # 绘制图形 ig.plot( g, vertex_label=g.vs['name'], vertex_size=20, vertex_label_color='white', bbox=(500, 400), margin=50 )
如果需要生成标签共现图,可修改边生成逻辑:将同一标题下的所有标签两两相连,无需保留标题节点即可。
内容的提问来源于stack exchange,提问作者user12217822
相关产品推荐
相关产品推荐

