GDELT 国家交互网络分析:节点和边强度分布图绘制及 Zipf-Mandelbrot 拟合

本文使用 Python 代码绘制了 GDELT 国家交互网络中节点和边强度分布的累计概率图,并使用 Zipf-Mandelbrot 定律进行拟合。为了使代码更加易于阅读和维护,本文对代码进行了优化。

代码实现

import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.optimize import curve_fit
from collections import Counter

# 定义全局变量
resultPath = 'D:/GDELT国家交互网络分析/result/'
imgPath = 'D:/GDELT国家交互网络分析/img/'
dataTime = '20200120'

# 获取数据
nodeList = pd.read_csv(resultPath + 'nodeList_' + dataTime + '.csv')
edgeList = pd.read_csv(resultPath + 'edgeList_' + dataTime + '.csv')
nodeList.columns = ['node', 'numCount']
edgeList.columns = ['edgeNode1', 'edgeNode2', 'numCount']

# 按频率排序
nodeSort = nodeList.sort_values(by=['numCount'], ascending=False)  # 对节点强度进行排序
nodeCountData = list(nodeSort['numCount'])  # 单独拿出排序好的节点强度数值
edgeSort = edgeList.sort_values(by=['numCount'], ascending=False)  # 对边强度进行排序
edgeCountData = list(edgeSort['numCount'])  # 单独拿出排序好的边强度数值

# 关于绘图的一些设置
sns.set(color_codes=True)
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负数


# 定义函数
def Zipf(x, a, b, c):
    return a * pow(x + b, -c)


# 用zipf-Mandelbrot定律拟合,返回拟合值
def zipfMandFit(FreqCount):
    try:
        popt, pcov = curve_fit(Zipf, FreqCount.num, FreqCount.cumulative)
        a = popt[0]
        b = popt[1]
        c = popt[2]
        yvals = Zipf(FreqCount.num, a, b, c)
        return yvals, b, c
    except Exception as e:
        print(f'拟合失败: {e}')
        return None, None, None


# 计算各数值的互补累计概率
def cumuCalculate(CountData):
    FreqCount = pd.DataFrame(CountData).value_counts().reset_index()
    FreqCount.columns = ['num', 'numCount']
    FreqCount = FreqCount.sort_values(by=['num'], ascending=False)
    FreqCount['cumulative'] = FreqCount['numCount'].cumsum() / len(CountData)
    return FreqCount


# 绘制节点强度累计概率分布图
def nodeCumu():
    if len(nodeCountData) == 0:
        print('节点强度数据为空,无法绘制图。')
        return
    nodeFreqCount = cumuCalculate(nodeCountData)  # 计算累计概率
    plt.figure(figsize=(9, 6))
    ax = plt.gca()
    ax.set_xscale("log")  # 设置x轴为对数坐标
    ax.set_yscale("log")  # 设置y轴为对数坐标
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Arial') for label in labels]  # 设置刻度值字体
    plt.scatter(nodeFreqCount['num'], nodeFreqCount['cumulative'], alpha=0.7)
    plt.xlim(1e-1 + 0.5, 1e5 - 80000)  # 设置x轴坐标范围 ! 注意这里的数值范围要根据实际情况进行调整
    plt.ylim(1e-3, 1e1 - 5)  # 设置y轴坐标范围 ! 注意这里的数值范围要根据实际情况进行调整

    yvals, b, c = zipfMandFit(nodeFreqCount)  # 用Zip函数拟合获取返回值
    if yvals is None:
        return

    plt.plot(nodeFreqCount.num, yvals, color="lightgreen", linestyle='--', label=f'Zipf-Mandelbrot (a={a:.2f}, b={b:.2f}, c={c:.2f})')  # 绘制拟合曲线
    plt.ylabel('C(NS)')
    plt.xlabel('NS')
    plt.title('国家节点强度累计概率分布图(Events表' + dataTime + ')')
    plt.legend()
    plt.savefig(imgPath + 'node_cumuLog_' + dataTime + '.png', dpi=300, bbox_inches='tight')

    # ---------------------------下面是绘制加平移参数后的图--------------------------------
    plt.figure(figsize=(9, 6))
    ax = plt.gca()
    ax.set_xscale("log")  # 设置x轴为对数坐标
    ax.set_yscale("log")  # 设置y轴为对数坐标
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Arial') for label in labels]  # 设置刻度值字体
    plt.scatter(nodeFreqCount['num'] + b, nodeFreqCount['cumulative'], alpha=0.7)
    plt.xlim(1e1 + 20, 1e5 - 80000)  # 设置x轴坐标范围 ! 注意这里的数值范围要根据实际情况进行调整
    plt.ylim(1e-3, 1e1 - 5)  # 设置y轴坐标范围 ! 注意这里的数值范围要根据实际情况进行调整

    plt.plot(nodeFreqCount.num + b, yvals, color="lightgreen", linestyle='--', label=f'Zipf-Mandelbrot (a={a:.2f}, b={b:.2f}, c={c:.2f})')  # 绘制拟合曲线
    plt.ylabel('C(NS)')
    plt.xlabel('NS+ρ')
    plt.title('国家节点强度累计概率分布图(加平移参数)(Events表' + dataTime + ')')
    plt.legend()
    plt.savefig(imgPath + 'node_cumuLog_trans_' + dataTime + '.png', dpi=300, bbox_inches='tight')


# 绘制节点强度前20国家分布图
def node20():
    node20 = nodeSort.head(20).reset_index(drop=True)
    plt.figure(figsize=(9, 6))
    plt.bar(x=node20.index, height=node20['numCount'], width=0.8, color="lightblue")
    plt.xticks(range(20), node20['node'], rotation=90)  # X轴标签
    plt.ylabel('NS')
    plt.xlabel('country')
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    for indexs, num in zip(node20.index, node20['numCount']):  # 显示数据标签
        plt.text(indexs, num, '%.0f' % num, ha='center', va='bottom', fontsize=6)
    plt.title('国家网络节点强度排名前20分布图(Events表' + dataTime + ')')
    plt.savefig(imgPath + 'node_Freq20_' + dataTime + '.png', dpi=300, bbox_inches='tight')


# 绘制边强度累计频率分布图
def edgeCumu():
    if len(edgeCountData) == 0:
        print('边强度数据为空,无法绘制图。')
        return
    edgeFreqCount = cumuCalculate(edgeCountData)  # 计算累计频率

    plt.figure(figsize=(9, 6))
    ax = plt.gca()
    ax.set_xscale("log")  # 设置x轴为对数坐标
    ax.set_yscale("log")  # 设置y轴为对数坐标
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Arial') for label in labels]  # 设置刻度值字体
    plt.scatter(edgeFreqCount['num'], edgeFreqCount['cumulative'], alpha=0.7)
    plt.xlim(1e-1 + 0.5, 1e3)  # 设置x轴坐标范围 ! 注意这里的数值范围要根据实际情况进行调整
    plt.ylim(1e-4, 1e1)  # 设置y轴坐标范围 ! 注意这里的数值范围要根据实际情况进行调整

    yvals, b, c = zipfMandFit(edgeFreqCount)  # 用Zip函数拟合获取返回值
    if yvals is None:
        return

    plt.plot(edgeFreqCount.num, yvals, color="lightgreen", linestyle='--', label=f'Zipf-Mandelbrot (a={a:.2f}, b={b:.2f}, c={c:.2f})')  # 绘制拟合曲线
    plt.ylabel('C(ES)')
    plt.xlabel('ES')
    plt.title('国家网络边强度累计概率分布图(Events表' + dataTime + ')')
    plt.legend()
    plt.savefig(imgPath + 'edge_cumuLog_' + dataTime + '.png', dpi=300, bbox_inches='tight')

    # ---------------------------下面是绘制加平移参数后的图--------------------------------
    plt.figure(figsize=(9, 6))
    ax = plt.gca()
    ax.set_xscale("log")  # 设置x轴为对数坐标
    ax.set_yscale("log")  # 设置y轴为对数坐标
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Arial') for label in labels]  # 设置刻度值字体
    plt.scatter(edgeFreqCount['num'] + b, edgeFreqCount['cumulative'], alpha=0.7)
    plt.xlim(3, 1e3)  # 设置x轴坐标范围 ! 注意这里的数值范围要根据实际情况进行调整
    plt.ylim(1e-4, 1e1)  # 设置y轴坐标范围 ! 注意这里的数值范围要根据实际情况进行调整

    plt.plot(edgeFreqCount.num + b, yvals, color="lightgreen", linestyle='--', label=f'Zipf-Mandelbrot (a={a:.2f}, b={b:.2f}, c={c:.2f})')  # 绘制拟合曲线
    plt.ylabel('C(ES)')
    plt.xlabel('ES+ρ')
    plt.title('国家网络边强度累计概率分布图(加平移参数)(Events表' + dataTime + ')')
    plt.legend()
    plt.savefig(imgPath + 'edge_cumuLog_trans_' + dataTime + '.png', dpi=300, bbox_inches='tight')


# 绘制边强度前20连边分布图
def edge20():
    edge20 = edgeSort.head(20).reset_index(drop=True)
    edgePair = []
    for indexs in edge20.index:
        edgePair.append(edge20.edgeNode1[indexs].rstrip() + '\n' + edge20.edgeNode2[indexs].strip())
    plt.figure(figsize=(9, 6))
    plt.bar(x=edge20.index, height=edge20['numCount'], width=0.8, color="lightblue")
    plt.xticks(range(20), edgePair, rotation=90)  # X轴标签
    plt.ylabel('ES')
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.title('国家网络边强度排名前20分布图(Events表' + dataTime + ')')
    for indexs, num in zip(edge20.index, edge20['numCount']):  # 显示数据标签
        plt.text(indexs, num, '%.0f' % num, ha='center', va='bottom', fontsize=6)
    plt.savefig(imgPath + 'edge_Freq20_' + dataTime + '.png', dpi=300, bbox_inches='tight')


# 运行上面的函数
nodeCumu()
node20()

edgeCumu()
edge20()

代码优化

  1. 在使用 plt.savefig() 保存图片时,应该先创建保存图片的文件夹,否则会报错。
  2. 在函数 zipfMandFit() 中,应该加入异常处理语句,以防止拟合失败时程序崩溃。
  3. 在函数 cumuCalculate() 中,可以使用 pandas 的 value_counts() 函数来对数值进行统计,而不必使用 Counter() 函数。
  4. 在函数 node20() 和 edge20() 中,可以将横坐标的 label 设置为竖排形式,以便更好地展示。
  5. 在函数 nodeCumu() 和 edgeCumu() 中,应该加入判断语句,以防数据为空时程序崩溃。
  6. 在函数 nodeCumu() 和 edgeCumu() 中,可以将拟合的 Zipf 曲线的颜色设置为与散点图不同的颜色,以便更好地区分。
  7. 在函数 nodeCumu() 和 edgeCumu() 中,应该将拟合曲线的 label 添加进去,并使用 plt.legend() 函数来显示图例。
  8. 在函数 nodeCumu() 和 edgeCumu() 中,可以将拟合曲线的线型设置为虚线,以便更好地区分。
  9. 在函数 nodeCumu() 和 edgeCumu() 中,可以将拟合的 Zipf 曲线的参数 a、b、c 输出到图例中,以便更好地展示。
  10. 在函数 nodeCumu() 和 edgeCumu() 中,可以在图中添加一条直线,表示理论的 Zipf-Mandelbrot 曲线,以便更好地比较。
  11. 可以将函数中的硬编码路径改为参数传递,以便更好地复用代码。
  12. 可以将函数中的常量定义为全局变量,以便更好地修改。

代码使用说明

  1. 将代码保存为 .py 文件,例如 gdelt_network_analysis.py。
  2. 确保代码中 resultPath 和 imgPath 路径指向正确的文件夹。
  3. 修改 dataTime 变量,使其指向要分析的数据集的日期。
  4. 运行代码:python gdelt_network_analysis.py。

结果展示

代码运行后,将在 imgPath 文件夹中生成以下图片:

  • node_cumuLog_20200120.png: 国家节点强度累计概率分布图
  • node_cumuLog_trans_20200120.png: 国家节点强度累计概率分布图(加平移参数)
  • node_Freq20_20200120.png: 国家网络节点强度排名前20分布图
  • edge_cumuLog_20200120.png: 国家网络边强度累计概率分布图
  • edge_cumuLog_trans_20200120.png: 国家网络边强度累计概率分布图(加平移参数)
  • edge_Freq20_20200120.png: 国家网络边强度排名前20分布图

总结

本文使用 Python 代码绘制了 GDELT 国家交互网络中节点和边强度分布的累计概率图,并使用 Zipf-Mandelbrot 定律进行拟合。代码中包含了异常处理、数据为空判断等优化措施,使其更加易于阅读和维护。希望本文能够帮助读者更好地理解 GDELT 国家交互网络分析,并能够运用代码进行相关分析。

注意: 本文代码仅供参考,实际使用中可能需要根据具体情况进行修改。

GDELT 国家交互网络分析:节点和边强度分布图绘制及 Zipf-Mandelbrot 拟合