1. 无向图

直接使用networkx所提供的相关函数。

  • 代码
import matplotlib.pyplot as plt  # 导入科学绘图包
import networkx as nx
import numpy as np

adj = np.loadtxt('adj.txt', dtype=np.int)  # 邻接矩阵
G = nx.from_numpy_matrix(adj)  # 网络
print("某个节点的度:", G.degree(0))  # 返回某个节点的度

# print("所有节点的度:",G.degree())#返回所有节点的度
# print("所有节点的度分布序列:",nx.degree_histogram(G))#返回图中所有节点的度分布序列(从1至最大度的出现频次)
degree = nx.degree_histogram(G)  # 返回图中所有节点的度分布序列

print(degree)
x = range(len(degree))  # 生成X轴序列,从1到最大度
y = [z / float(sum(degree)) for z in degree]  # 将频次转化为频率
plt.figure(figsize=(5.8, 5.2), dpi=150)
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.xlabel("Degree", size=14)  # Degree
plt.ylabel("Frequency", size=14)  # Frequency
plt.xticks(fontproperties='Times New Roman', size=13)
plt.yticks(fontproperties='Times New Roman', size=13)
plt.loglog(x, y, '.')
plt.show()  # 显示图表
  • 效果图(与有向图 3 一致)
    在这里插入图片描述

2. 有向图

  • 代码
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from collections import Counter

'''
统计表方法
csv文件 每行[id,indegree,outdegree,degree]
画度分布图
'''
data = pd.read_csv('度.csv') # 数据类型为每个节点的度值
namelist = ['入度', '出度', '度']

for i in range(1,4):
    # 数据列,
    degree = np.array(data.iloc[:,[0,i]])
    # 分布统计
    counts = Counter(d for n, d in degree)
    b = [counts.get(i, 0) for i in range(max(counts) + 1)]
    x = range(len(b)) # x轴
    y = [z for z in b] # y轴
    # 画图
    plt.figure(figsize=(5.8, 5.2), dpi=150)
    plt.xlabel("Degree")
    plt.ylabel("Frequency")
    plt.xticks(fontproperties='Times New Roman', size=14)
    plt.yticks(fontproperties='Times New Roman', size=14)
    plt.loglog(x, y, '.')
    plt.savefig('figure/'+namelist[i-1]+'分布图.png') # 保存图片
    plt.show()
  • 效果图
    入度
    入度
    出度
    出度

    度
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐