## 节点 Nodes# libraries 载入库import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# Build a dataframe with your connections
df = pd.DataFrame({'from':['A','B','C','A'],'to':['D','A','E','C']})
df
# Build your graph 建立表格
G=nx.from_pandas_edgelist(df,'from','to')# Graph with Custom nodes: 自定义表格# with_labels是否显示标签,node_size节点大小,node_color节点颜色,node_shape节点形状,alpha透明度,linewidths线条宽度
nx.draw(G, with_labels=True, node_size=1500, node_color="skyblue", node_shape="s", alpha=0.5, linewidths=10)
plt.show()
from
to
0
A
D
1
B
A
2
C
E
3
A
C
## 标签 Labels# librariesimport pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# Build a dataframe with your connections
df = pd.DataFrame({'from':['A','B','C','A'],'to':['D','A','E','C']})
df
# Build your graph
G=nx.from_pandas_edgelist(df,'from','to')# Custom the edges:# font_size标签字体大小,font_color标签字体颜色,font_weight字体形式
nx.draw(G, with_labels=True, node_size=1500, font_size=25, font_color="yellow", font_weight="bold")
plt.show()
from
to
0
A
D
1
B
A
2
C
E
3
A
C
## 边 Edges# librariesimport pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# Build a dataframe with your connections
df = pd.DataFrame({'from':['A','B','C','A'],'to':['D','A','E','C']})
df
# Build your graph
G=nx.from_pandas_edgelist(df,'from','to')# Chart with Custom edges:# width边线条宽,edge_color边线条颜色
nx.draw(G, with_labels=True, width=10, edge_color="skyblue", style="solid")
from
to
0
A
D
1
B
A
2
C
E
3
A
C
## 总结 All# librariesimport pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# Build a dataframe with your connections
df = pd.DataFrame({'from':['A','B','C','A'],'to':['D','A','E','C']})
df
# Build your graph
G=nx.from_pandas_edgelist(df,'from','to')# All together we can do something fancy
nx.draw(G, with_labels=True, node_size=1500, node_color="skyblue", node_shape="o", alpha=0.5, linewidths=4, font_size=25, font_color="grey", font_weight="bold", width=2, edge_color="grey")
# librariesimport pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# Build a dataframe with your connections
df = pd.DataFrame({'from':['A','B','C','A','E','F','E','G','G','D','F'],'to':['D','A','E','C','A','F','G','D','B','G','C']})
df
# Build your graph
G=nx.from_pandas_edgelist(df,'from','to')
# librariesimport pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
## DIRECTED 有向图# Build a dataframe with your connections# This time a pair can appear 2 times, in one side or in the other!
df = pd.DataFrame({'from':['D','A','B','C','A'],'to':['A','D','A','E','C']})
df
# Build your graph. Note that we use the DiGraph function to create the graph!# create_using=nx.DiGraph()创建有向图,默认是无向图
G=nx.from_pandas_edgelist(df,'from','to', create_using=nx.DiGraph())# Make the graph 有向图
nx.draw(G, with_labels=True, node_size=1500, alpha=0.3, arrows=True)
from
to
0
D
A
1
A
D
2
B
A
3
C
E
4
A
C
# UNDIRECTED 无向图# Build a dataframe with your connections# This time a pair can appear 2 times, in one side or in the other!
df = pd.DataFrame({'from':['D','A','B','C','A'],'to':['A','D','A','E','C']})
df
# Build your graph. Note that we use the Graph function to create the graph!
G=nx.from_pandas_edgelist(df,'from','to', create_using=nx.Graph())# Make the graph
nx.draw(G, with_labels=True, node_size=1500, alpha=0.3, arrows=True)
plt.title("UN-Directed")
## Continuous color scale 连续颜色# librariesimport pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# Build a dataframe with your connections
df = pd.DataFrame({'from':['A','B','C','A'],'to':['D','A','E','C']})# And a data frame with characteristics for your nodes
carac = pd.DataFrame({'ID':['A','B','C','D','E'],'myvalue':['123','25','76','12','34']})# 设置值
carac
# Build your graph 建立图
G =nx.from_pandas_edgelist(df,'from','to', create_using=nx.Graph())# The order of the node for networkX is the following order:# 节点顺序
G.nodes()# Thus, we cannot give directly the 'myvalue' column to netowrkX, we need to arrange the order!# Here is the tricky part: I need to reorder carac, to assign the good color to each node# 根据myvalue设置颜色,并匹配节点顺序和ID号
carac = carac.set_index('ID')
carac =carac.reindex(G.nodes())
carac
# Plot it, providing a continuous color scale with cmap:# node_color设定颜色,输入的必须是float数组或者int值;cmap颜色条
nx.draw(G, with_labels=True, node_color=np.array(carac['myvalue'].values,dtype='float32'), cmap=plt.cm.Blues)
ID
myvalue
0
A
123
1
B
25
2
C
76
3
D
12
4
E
34
NodeView(('A', 'D', 'B', 'C', 'E'))
myvalue
ID
A
123
D
12
B
25
C
76
E
34
## Categorical color scale 连续颜色# librariesimport pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# Build a dataframe with your connections
df = pd.DataFrame({'from':['A','B','C','A'],'to':['D','A','E','C']})# And a data frame with characteristics for your nodes
carac = pd.DataFrame({'ID':['A','B','C','D','E'],'myvalue':['group1','group1','group2','group3','group3']})# Build your graph# 建立图
G=nx.from_pandas_edgelist(df,'from','to', create_using=nx.Graph())# The order of the node for networkX is the following order:# 打印节点顺序
G.nodes()# Thus, we cannot give directly the 'myvalue' column to netowrkX, we need to arrange the order!# Here is the tricky part: I need to reorder carac to assign the good color to each node
carac= carac.set_index('ID')# 根据节点顺序设定值
carac=carac.reindex(G.nodes())# And I need to transform my categorical column in a numerical value: group1->1, group2->2...# 设定类别
carac['myvalue']=pd.Categorical(carac['myvalue'])
carac['myvalue'].cat.codes
# Custom the nodes:
nx.draw(G, with_labels=True, node_color=carac['myvalue'].cat.codes, cmap=plt.cm.Set1, node_size=1500)
NodeView(('A', 'D', 'B', 'C', 'E'))
ID
A 0
D 2
B 0
C 1
E 2
dtype: int8
6. 将颜色映射到网络的边 Map colour to the edges of a Network
## 数值型 numerical# librariesimport pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# Build a dataframe with your connections# value设定链接值
df = pd.DataFrame({'from':['A','B','C','A'],'to':['D','A','E','C'],'value':[1,10,5,5]})
df
# Build your graph
G=nx.from_pandas_edgelist(df,'from','to', create_using=nx.Graph())# Custom the nodes:# edge_color设置边的颜色
nx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_color=df['value'], width=10.0, edge_cmap=plt.cm.Blues)
from
to
value
0
A
D
1
1
B
A
10
2
C
E
5
3
A
C
5
## 类别型 categorical# librariesimport pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# Build a dataframe with your connections# value设置类型
df = pd.DataFrame({'from':['A','B','C','A'],'to':['D','A','E','C'],'value':['typeA','typeA','typeB','typeB']})
df
# And I need to transform my categorical column in a numerical value typeA->1, typeB->2...# 转换为类别
df['value']=pd.Categorical(df['value'])
df['value'].cat.codes
# Build your graph
G=nx.from_pandas_edgelist(df,'from','to', create_using=nx.Graph())# Custom the nodes:
nx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_color=df['value'].cat.codes, width=10.0, edge_cmap=plt.cm.Set2)
# librariesimport pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# Build a dataframe with your connections
df = pd.DataFrame({'from':['A','B','C','A'],'to':['D','A','E','C']})
df
# Build your graph
G=nx.from_pandas_edgelist(df,'from','to', create_using=nx.Graph())# Custom the nodes:
fig = plt.figure()
nx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_color='white')# 设置背景颜色
fig.set_facecolor("#00000F")# If you want to save the figure to png:# 保存图像需要设定facecolor=fig.get_facecolor() ,否者背景颜色为白色# plt.savefig('yourname.png', facecolor=fig.get_facecolor(),dpi=300)
# librariesimport pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# I build a data set: 10 individuals and 5 variables for each
ind1=[5,10,3,4,8,10,12,1,9,4]
ind5=[1,1,13,4,18,5,2,11,3,8]# 建立矩阵
df = pd.DataFrame({'A':ind1,'B':ind1 + np.random.randint(10, size=(10)),'C':ind1 + np.random.randint(10, size=(10)),'D':ind1 + np.random.randint(5, size=(10)),'E':ind1 + np.random.randint(5, size=(10)),'F':ind5,'G':ind5 + np.random.randint(5, size=(10)),'H':ind5 + np.random.randint(5, size=(10)),'I':ind5 + np.random.randint(5, size=(10)),'J':ind5 + np.random.randint(5, size=(10))})
df
# Calculate the correlation between individuals. We have to transpose first, because the corr function calculate the pairwise correlations between columns.# 计算相关性
corr = df.corr()
corr
# Transform it in a links data frame (3 columns only):# 将相关系数矩阵压平
links = corr.stack().reset_index()# 设置列名
links.columns =['var1','var2','value']#links# Keep only correlation over a threshold and remove self correlation (cors (A,A)=1)# 剔除相同编号的行以及相关系数小于0.8的行
links_filtered=links.loc[(links['value']>0.8)&(links['var1']!= links['var2'])]#links_filtered# Build your graph# 作图
G=nx.from_pandas_edgelist(links_filtered,'var1','var2')# Plot the network:
nx.draw(G, with_labels=True, node_color='orange', node_size=500, edge_color='black', linewidths=5, font_size=15)
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)