当前位置:首页>python>Python绘制双层关系网络图(附数据和代码)

Python绘制双层关系网络图(附数据和代码)

  • 2026-09-15 11:00:56
Python绘制双层关系网络图(附数据和代码)

©[悠悠智汇笔记] 版权所有

🙏请尊重劳动成果,守护每一份劳动心血;⚖️未经授权,不得以为任何方式转载、摘编或抄袭。🔄转载合作请后台联系授权,侵权必究。

本期分享基于论文数据绘制的双层网络关系图。其中,底层为论文节点及其引用关系网络,用于反映知识之间的传播与关联;顶层为作者节点及其合作关系网络,用于反映学者之间的合作关系;两层之间通过作者—论文署名关系进行连接。图中节点大小按照节点度进行缩放,度值越高表示该节点与其他节点的连接越多,因而在网络中具有更高的重要性或更强的影响力。

01

初始化图对象

从 CSV 文件中读取节点和边数据,并创建一个空的网络图对象。

import pandas as pdimport networkx as nximport matplotlib.pyplotas pltimport numpy as np# 读取节点和边数据nodes_df = pd.read_csv('sci_nodes.csv')edges_df = pd.read_csv('sci_edges.csv')# 初始化无向图G = nx.Graph()

02

节点和边

将表格中的节点属性和边关系逐条写入网络图,形成完整的图结构。

# 加入节点for_, row in nodes_df.iterrows():    G.add_node(        row['id'],        lvl=row['lvl'],        label=row['lvl']    )# 加入边for_, row in edges_df.iterrows():    G.add_edge(        row['source'],        row['target'],        rel=row['rel']    )# 计算节点度node_degrees = dict(G.degree())

03

双层网络布局

通过弹簧布局和等轴测投影,把两层节点映射到更有层次感的二维画布上。

def sci_multilevel_layout(G):    # 先生成基础二维布局    pos_base = nx.spring_layout(G, k=0.15, iterations=100, seed=42)    # 定义投影角度    alpha, beta = np.radians(20), np.radians(40)    pos_2d = {}    for node, (x, z) in pos_base.items():        # 根据层级设置高度        y = 1 if G.nodes[node]['lvl'] == 2 else 0.0        # 等轴测投影公式        xp = x * np.cos(beta) + z * np.sin(beta)        pos_2d[node] = np.array([xp, yp])    return pos_2d

04

计算坐标

根据布局结果,把不同关系的边和不同层级的节点分别绘制出来。

plt.figure(figsize=(16, 10), facecolor='#FAFAFA')# 按关系类型筛选边e_auth = [(u, v) for u, v, d in G.edges(data=True) if d['rel'] == 'authorship']e_cit = [(u, v) for u, v, d in G.edges(data=True) if d['rel'] == 'citation']e_col = [(u, v) for u, v, d in G.edges(data=True) if d['rel'] == 'collaboration']# 绘制边nx.draw_networkx_edges(G, pos, edgelist=e_auth, edge_color='gray', alpha=0.3, width=0.3)nx.draw_networkx_edges(G, pos, edgelist=e_cit, edge_color='hotpink', alpha=0.3, width=0.6)nx.draw_networkx_edges(G, pos, edgelist=e_col, edge_color='#95c8e7', alpha=0.5, width=1.0)# 按层级筛选节点authors = [n for n, d in G.nodes(data=True) if d['lvl'] == 2]papers = [n for n, d in G.nodes(data=True) if d['lvl'] == 1]# 计算节点大小author_sizes = [10 + node_degrees[n] * 15 for n in authors]paper_sizes = [10 + node_degrees[n] * 15 for n in papers]# 绘制节点nx.draw_networkx_nodes(    G, pos,    nodelist=authors,    node_shape='s',    node_color='#95c8e7',    node_size=author_sizes,    edgecolors='#1D4E89',    linewidths=0.8,    label='Authors')nx.draw_networkx_nodes(    G, pos,    nodelist=papers,    node_shape='o',    node_color='hotpink',    node_size=paper_sizes,    alpha=0.8,    edgecolors='#C71585',    linewidths=0.6,    label='Papers')

🌿 今日的分享就到这里啦~如果这些内容有为你带来帮助,欢迎轻点右下角的【👍赞】和【👀在看】,也欢迎分享给更多需要的人,感恩~

THE

END

数据和代码怎么获取?

点击关注后,后台回复关键词:

2026_map_016可直接获取完整的示例数据和代码

如有帮助,您的点赞、评论、转发是我持续创作的动力~

猜您喜欢
往期精选▼

1.Python绘制SHAP+蜂巢图(附数据和代码)

2.Python绘制切尔斯图(附数据和代码)

3.Python绘制顶刊同款散点拟合回归组合图(附数据和代码)

#数据可视化#科研绘图 #环状热图 #Python #Matplotlib #Pycirclize

最新文章

随机文章